From 16227901fc74c9018ac3e4d32141256c63897ed9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:05:18 +0200 Subject: [PATCH 1/7] Check the crafter against vanilla with a crafting harness CrafterBlock.dispenseFrom and CrafterBlockEntity.serverTick over 4,000 cases: recipes from the datapack with remainders and specials, disabled slots, containers and other crafters in front. The crafter now reports its level events (1049, 1050, white smoke 2010) through the client random, hoppers merge stacks only with equal components, brewing stands take items as a WorldlyContainer, and empty written book pages are not written. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/containers.rs | 4 +- .../src/game/dispense_fixture.rs | 63 ++++ crates/horizon-client/src/game/dispenser.rs | 18 +- crates/horizon-client/src/game/machines.rs | 47 ++- .../src/game/machines/crafter.rs | 43 +-- crates/horizon-client/src/item_data.rs | 5 +- .../parity/VanillaBlockUpdateOracle.java | 4 + .../parity/VanillaDispenserOracle.java | 51 +++- tools/test_crafter_parity.py | 277 ++++++++++++++++++ 9 files changed, 461 insertions(+), 51 deletions(-) create mode 100644 tools/test_crafter_parity.py diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 46447eb1c..501d9214a 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -97,7 +97,7 @@ impl Crafter { .count() as i32 } /// `canPlaceItem`: a hopper fills the smallest stacks first. - pub fn can_place(&self, slot: usize, stack: &ItemStack, max_stack: u32) -> bool { + pub fn can_place(&self, slot: usize, _stack: &ItemStack, max_stack: u32) -> bool { if slot >= 9 || self.disabled[slot] { return false; } @@ -112,7 +112,7 @@ impl Crafter { && match &self.items[i] { None => true, Some(other) => { - other.count < current.count && other.same_item_same_components(stack) + other.count < current.count && other.same_item_same_components(current) } } }) diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index a906ba259..f23a515be 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -188,6 +188,39 @@ impl Game<'_> { *cell = stack; } } + // CrafterBlock.newBlockEntity copies the state's triggered flag; + // CrafterBlockEntity.setSlotState disables only empty slots. + let crafter_positions: Vec<(i32, i32, i32)> = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) + .map(|(p, _)| *p) + .collect(); + for p in crafter_positions { + let state = self.world.block(p.0, p.1, p.2); + let triggered = self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("triggered")) + .is_some_and(|v| v == "true"); + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&p) { + c.triggered = triggered; + c.state_triggered = Some(triggered); + } + } + for d in case["disabled"].as_array().into_iter().flatten() { + let p = ( + d[0].as_i64().unwrap_or(0) as i32, + d[1].as_i64().unwrap_or(0) as i32, + d[2].as_i64().unwrap_or(0) as i32, + ); + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&p) { + c.set_slot_state(d[3].as_u64().unwrap_or(0) as usize, false); + } + } let mut targets = Vec::new(); for e in case["entities"].as_array().into_iter().flatten() { targets.push(self.fixture_target(e)?); @@ -226,6 +259,10 @@ impl Game<'_> { ); let state = self.world.block(origin.x, origin.y, origin.z); self.dispense_from(origin, state)?; + // CrafterBlockEntity.serverTick, the crafting animation running down. + for _ in 0..case["ticks"].as_u64().unwrap_or(0) { + self.tick_crafters(); + } let mut out = Vec::new(); let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default(); @@ -253,6 +290,32 @@ impl Game<'_> { } } } + let mut crafters: Vec<_> = self + .world + .block_entities + .iter() + .filter_map(|(p, e)| match e { + BlockEntity::Crafter(c) => Some((*p, c)), + _ => None, + }) + .collect(); + crafters.sort_unstable_by_key(|c| c.0); + for (p, c) in crafters { + let disabled: Vec = (0..9) + .filter(|&i| c.disabled[i]) + .map(|i| i.to_string()) + .collect(); + out.push(format!( + "crafter {},{},{} ticks={} triggered={} signal={} disabled={}", + p.0, + p.1, + p.2, + c.crafting_ticks, + c.triggered, + c.redstone_signal(), + disabled.join(",") + )); + } self.fixture_entities(&old_mobs, &old_stands, &mut out); for (i, t) in targets.iter().enumerate() { out.push(self.fixture_describe(i, t)); diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index f6a7e5a58..00b4ea22c 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -387,7 +387,20 @@ impl Game<'_> { self.audio .play("minecraft:entity.wind_charge.throw", Some(c), 0.5, pitch); } - 2000 => { + 1049 => self + .audio + .play("minecraft:block.crafter.craft", Some(c), 1.0, 1.0), + 1050 => self + .audio + .play("minecraft:block.crafter.fail", Some(c), 1.0, 1.0), + // LevelEventHandler.shootParticles: smoke for dispensers, white + // smoke out of a crafter's front. + 2000 | 2010 => { + let particle = if id == 2010 { + ParticleType::WhiteSmoke + } else { + ParticleType::Smoke + }; let s = match data { 0 => [0, -1, 0], 1 => [0, 1, 0], @@ -422,8 +435,7 @@ impl Game<'_> { sy * pow + r.next_gaussian() * 0.01, sz * pow + r.next_gaussian() * 0.01, ]; - self.particles - .add(&ParticleOptions::simple(ParticleType::Smoke), p, v); + self.particles.add(&ParticleOptions::simple(particle), p, v); } } _ => {} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index e6c73a13b..386b6a7bb 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -39,6 +39,8 @@ enum Kind { Hopper, /// `CrafterBlockEntity`: disabled slots and the smallest-stack-first rule. Crafter, + /// `BrewingStandBlockEntity` (a `WorldlyContainer`). + Brewing, } /// A container: one block entity, or a double chest (`CompoundContainer`). @@ -66,6 +68,9 @@ impl View { (Kind::Furnace, Some(Direction::Down)) => vec![2, 1], (Kind::Furnace, Some(Direction::Up)) => vec![0], (Kind::Furnace, Some(_)) => vec![1], + (Kind::Brewing, Some(Direction::Up)) => vec![3], + (Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3], + (Kind::Brewing, Some(_)) => vec![0, 1, 2, 4], _ => (0..self.len()).collect(), } } @@ -112,6 +117,8 @@ struct Containers<'a> { behaviours: &'a Behaviours, items: &'a Items, registry: &'static horizon_world::registry::BlockRegistry, + /// Brewing recipes, for what a brewing stand accepts (not needed for signals). + brewing: Option<&'a horizon_client::brewing::Brewing>, } impl Containers<'_> { fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> { @@ -140,6 +147,7 @@ impl Containers<'_> { let kind = match (entity, name) { (BlockEntity::Furnace(_), _) => Kind::Furnace, (BlockEntity::Crafter(_), _) => Kind::Crafter, + (BlockEntity::Brewing(_), _) => Kind::Brewing, (_, "minecraft:hopper") => Kind::Hopper, _ => Kind::Generic, }; @@ -209,10 +217,33 @@ impl Containers<'_> { fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool { if view.kind == Kind::Crafter { return match self.world.block_entities.get(&view.parts[0].0) { - Some(BlockEntity::Crafter(c)) => c.can_place(slot, stack, self.max_stack(stack)), + Some(BlockEntity::Crafter(c)) => { + // The slot's own stack sets the limit (`slotStack.getMaxStackSize`). + let max = c.items.get(slot).and_then(Option::as_ref).unwrap_or(stack); + c.can_place(slot, stack, self.max_stack(max)) + } _ => false, }; } + if view.kind == Kind::Brewing { + // BrewingStandBlockEntity.canPlaceItem + return match slot { + 4 => self + .items + .get(&stack.item) + .is_some_and(|i| i.brewing_fuel.is_some()), + 3 => self.brewing.is_some_and(|b| b.is_reagent(stack)), + _ => { + let input = self.brewing.is_some_and(|b| b.is_bottle(stack)) + || self + .items + .item_tags + .get("minecraft:brewing_potion_inputs") + .is_some_and(|m| m.contains(&*stack.item)); + input && self.get(view, slot).is_none() + } + }; + } if view.kind != Kind::Furnace { return true; } @@ -231,8 +262,11 @@ impl Containers<'_> { _ => true, } } - /// `canTakeItemThroughFace` (only furnaces restrict it). + /// `canTakeItemThroughFace` (furnaces and brewing stands restrict it). fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool { + if view.kind == Kind::Brewing { + return slot != 3 || &*stack.item == "minecraft:glass_bottle"; + } view.kind != Kind::Furnace || face != Direction::Down || slot != 1 @@ -279,6 +313,7 @@ pub(super) fn container_signal( behaviours, items, registry, + brewing: None, }; c.view((pos.x, pos.y, pos.z), true) .map_or(0, |v| c.signal(&v)) @@ -291,6 +326,7 @@ impl Game<'_> { behaviours: &self.res.behaviours, items: &self.res.items, registry: self.res.assets.registry, + brewing: Some(&self.res.stations.brewing), } } fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option> { @@ -346,9 +382,8 @@ impl Game<'_> { success = true; } Some(current) - if current.item == stack.item - && current.damage == stack.damage - && current.count <= max => + // HopperBlockEntity.canMergeItems + if current.count <= max && current.same_item_same_components(&stack) => { let space = max.saturating_sub(current.count); let count = stack.count.min(space); @@ -380,7 +415,7 @@ impl Game<'_> { stack: ItemStack, face: Option, ) -> Option { - let slots = if view.kind == Kind::Furnace && face.is_some() { + let slots = if matches!(view.kind, Kind::Furnace | Kind::Brewing) && face.is_some() { view.slots_for_face(face) } else { (0..view.len()).collect() diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index af37192ff..ea795fe35 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -7,7 +7,6 @@ use horizon_client::{ advancements as adv, containers::Crafter, hud::{HudBatch, rgba}, - particles::{ParticleOptions, ParticleType}, }; use serde_json::Value; @@ -67,6 +66,8 @@ impl Game<'_> { .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) .map(|(p, _)| *p) .collect(); + let mut positions = positions; + positions.sort_unstable(); for pos in positions { let state = self.world.block(pos.0, pos.1, pos.2); let triggered = self.containers().prop(state, "triggered") == Some("true"); @@ -101,6 +102,7 @@ impl Game<'_> { return Ok(()); }; let grid: Vec> = crafter.items.to_vec(); + // RecipeCache.get: the first crafting recipe that matches, assembled. let found = self .res .recipes @@ -108,9 +110,7 @@ impl Game<'_> { .map(|(name, result)| (name.to_owned(), result)) .filter(|(_, result)| result.count > 0); let Some((recipe, result)) = found else { - // LevelEvent 1050: CRAFTER_FAIL. - self.audio - .play("minecraft:block.crafter.fail", Some(center(key)), 1.0, 1.0); + self.dispenser_event(1050, key, 0); return Ok(()); }; let Some(facing) = self @@ -130,6 +130,7 @@ impl Game<'_> { true, horizon_world::level::flags::UPDATE_CLIENTS, ); + // The remainders come from the grid as it was before anything moved. let remainders = self.res.recipes.remainders(&recipe, &grid, 3); self.crafter_eject(key, facing, result, &recipe); for rest in remainders.into_iter().flatten() { @@ -184,38 +185,6 @@ impl Game<'_> { return; } self.spawn_dispensed(pos, facing, rest, 6); - // LevelEvent 1049 (CRAFTER_CRAFT) and 2010 (white smoke shot out the front). - self.audio - .play("minecraft:block.crafter.craft", Some(center(pos)), 1.0, 1.0); - let s = step(facing); - for _ in 0..10 { - let r = &mut self.world.random; - let pow = r.next_double() * 0.2 + 0.01; - let at = [ - f64::from(pos.0) - + f64::from(s[0]) * 0.6 - + 0.5 - + f64::from(s[0]) * 0.01 - + (r.next_double() - 0.5) * f64::from(s[2]) * 0.5, - f64::from(pos.1) - + f64::from(s[1]) * 0.6 - + 0.5 - + f64::from(s[1]) * 0.01 - + (r.next_double() - 0.5) * f64::from(s[1]) * 0.5, - f64::from(pos.2) - + f64::from(s[2]) * 0.6 - + 0.5 - + f64::from(s[2]) * 0.01 - + (r.next_double() - 0.5) * f64::from(s[0]) * 0.5, - ]; - let v = [ - f64::from(s[0]) * pow + r.next_gaussian() * 0.01, - f64::from(s[1]) * pow + r.next_gaussian() * 0.01, - f64::from(s[2]) * pow + r.next_gaussian() * 0.01, - ]; - self.particles - .add(&ParticleOptions::simple(ParticleType::WhiteSmoke), at, v); - } // CrafterRecipeCraftedTrigger for players within the 17-block box. let near = self.eye_position().is_some_and(|e| { let c = center(pos); @@ -234,6 +203,8 @@ impl Game<'_> { adv::conditions(&c["player"], &ctx, w) && recipe_matches(&c["recipes"], &id) }); } + self.dispenser_event(1049, pos, 0); + self.dispenser_event(2010, pos, facing as i32); } // ---- the menu ---- diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index e4329a140..46e7865a3 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -478,8 +478,11 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { 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)), ]; + // `optionalFieldOf("pages", List.of())`: no pages, no field. + if !w.pages.is_empty() { + fields.push(("pages", Tag::List(pages))); + } if w.generation != 0 { fields.push(("generation", Tag::Int(i32::from(w.generation)))); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index 606e2ae34..7ea2b095a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -187,6 +187,7 @@ public final class VanillaBlockUpdateOracle { @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; } @Override public GameRules getGameRules() { return rules; } @Override public net.minecraft.server.MinecraftServer getServer() { return server; } + @Override public net.minecraft.world.item.crafting.RecipeManager recipeAccess() { return Server.recipes; } @Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return new net.minecraft.world.level.border.WorldBorder(); } @Override public int getSeaLevel() { return 63; } @Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? skyLight : blockLight; } @@ -424,6 +425,9 @@ public final class VanillaBlockUpdateOracle { Server() { super(null, null, null, null, null, null, null, null, null, false, null); } + /** Crafting recipes, for the oracles that craft (the crafter); null elsewhere. */ + static net.minecraft.world.item.crafting.RecipeManager recipes; + @Override public net.minecraft.world.item.crafting.RecipeManager getRecipeManager() { return recipes; } @Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return loot; } @Override protected boolean initServer() { return false; } @Override public int getMaxPlayers() { return 0; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 26bb9a745..b70ac5c16 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -19,7 +19,9 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.CrafterBlock; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.CrafterBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gamerules.GameRules; import net.minecraft.world.level.levelgen.LegacyRandomSource; @@ -44,6 +46,8 @@ public final class VanillaDispenserOracle { case 1002 -> "minecraft:block.dispenser.launch"; case 1004 -> "minecraft:entity.firework_rocket.shoot"; case 1018 -> "minecraft:entity.blaze.shoot"; + case 1049 -> "minecraft:block.crafter.craft"; + case 1050 -> "minecraft:block.crafter.fail"; case 1051 -> "minecraft:entity.wind_charge.throw"; case 1505 -> "minecraft:item.bone_meal.use"; case 1501 -> "minecraft:block.lava.extinguish"; @@ -67,6 +71,9 @@ public final class VanillaDispenserOracle { field.setAccessible(true); VanillaBlockUpdateOracle.unsafe = field.get(null); VanillaBlockUpdateOracle.allocate = allocator.getMethod("allocateInstance", Class.class); + var recipes = new net.minecraft.world.item.crafting.RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.VANILLA_SET); + VanillaBlockUpdateOracle.Server.recipes = recipes; try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) { int index = 0; for (var line : (Iterable) lines::iterator) { @@ -208,6 +215,13 @@ public final class VanillaDispenserOracle { slots(w.getBlockEntity(at)).set(it.get(3).getAsInt(), stack(it.get(4).getAsString())); } } + if (f.has("disabled")) { + for (var d : f.getAsJsonArray("disabled")) { + var it = d.getAsJsonArray(); + BlockPos at = new BlockPos(it.get(0).getAsInt(), it.get(1).getAsInt(), it.get(2).getAsInt()); + ((CrafterBlockEntity) w.getBlockEntity(at)).setSlotState(it.get(3).getAsInt(), false); + } + } if (f.has("entities")) { List created = new ArrayList<>(); for (var e : f.getAsJsonArray("entities")) { @@ -232,11 +246,35 @@ public final class VanillaDispenserOracle { List targets = List.copyOf(w.entities); BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos")); BlockState state = w.getBlockState(origin); - dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin); + if (state.getBlock() instanceof CrafterBlock) { + Method craft = CrafterBlock.class.getDeclaredMethod("dispenseFrom", BlockState.class, ServerLevel.class, BlockPos.class); + craft.setAccessible(true); + craft.invoke(state.getBlock(), state, w, origin); + // CrafterBlockEntity.serverTick for every crafter, the animation running down. + int ticks = f.has("ticks") ? f.get("ticks").getAsInt() : 0; + for (int t = 0; t < ticks; t++) { + for (BlockPos at : sortedEntities(w)) { + if (w.getBlockEntity(at) instanceof CrafterBlockEntity crafter) { + CrafterBlockEntity.serverTick(w, at, w.getBlockState(at), crafter); + } + } + } + } else { + dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin); + } result.addAll(VanillaBlockUpdateOracle.summary(w, before)); - List containers = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); - containers.sort(Comparator.comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ())); + List containers = sortedEntities(w); + for (BlockPos at : containers) { + if (w.blockEntities.get(at) instanceof CrafterBlockEntity crafter && w.getBlockEntity(at) == crafter) { + Field ticksField = CrafterBlockEntity.class.getDeclaredField("craftingTicksRemaining"); + ticksField.setAccessible(true); + StringBuilder disabled = new StringBuilder(); + for (int i = 0; i < 9; i++) if (crafter.isSlotDisabled(i)) disabled.append(disabled.length() > 0 ? "," : "").append(i); + result.add("crafter " + VanillaBlockUpdateOracle.pos(at) + " ticks=" + ticksField.getInt(crafter) + " triggered=" + crafter.isTriggered() + + " signal=" + crafter.getRedstoneSignal() + " disabled=" + disabled); + } + } for (BlockPos at : containers) { if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue; var items = slots(w.blockEntities.get(at)); @@ -268,6 +306,13 @@ public final class VanillaDispenserOracle { result.add("rng " + w.rng.nextLong()); } + /** The level's block entity positions by x, y, z. */ + static List sortedEntities(VanillaBlockUpdateOracle.World w) { + List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); + out.sort(Comparator.comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ())); + return out; + } + /** A target's state after dispensing: removal, equipment and readiness for shearing. */ static String describe(int index, Entity e) { StringBuilder line = new StringBuilder("T " + index + " " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType())); diff --git a/tools/test_crafter_parity.py b/tools/test_crafter_parity.py new file mode 100644 index 000000000..1b9564f41 --- /dev/null +++ b/tools/test_crafter_parity.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python3 +"""Compare vanilla's crafter with Horizon's, one redstone-triggered craft per case. + +A crafter at the origin, in one of its twelve orientations, holds a grid +filled from a random vanilla crafting recipe (any recipe of the datapack, the +cake and other recipes with remainders, special recipes, or junk that matches +nothing), with some empty slots disabled. In front stands a container (chest, +hopper, barrel, dropper, furnace, shulker box, another crafter with its own +grid and disabled slots, sometimes nearly full), a solid block, water or air. +Vanilla `CrafterBlock.dispenseFrom` runs over the headless level of the block +update oracle (`VanillaDispenserOracle`), followed by a few +`CrafterBlockEntity.serverTick`s; Horizon runs its game glue in a headless +game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes (the crafting +flag set and cleared), every container's contents, each crafter's animation +ticks, triggered flag, comparator signal and disabled slots, the items shot +out with their motion, level events, sounds and the level random. +""" +import json +import os +import random +import subprocess +try: + from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base +except ImportError: + import block_update_harness as h + import lab + import test_dispenser_parity as d + import test_rust_parity as base + +FRONTS = ['north_up', 'south_up', 'west_up', 'east_up', 'up_north', 'up_south', 'up_west', 'up_east', + 'down_north', 'down_south', 'down_west', 'down_east'] +STEP = {'down': (0, -1, 0), 'up': (0, 1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)} +FRONT_BLOCKS = ['air', 'air', 'air', 'chest', 'chest', 'hopper', 'barrel', 'dropper', 'dispenser', 'crafter', 'crafter', + 'furnace', 'blast_furnace', 'smoker', 'shulker_box', 'stone', 'water', 'trapped_chest', 'brewing_stand'] +# Recipes whose remainders the crafter shoots out too, and specials. +FAVOURITES = ['cake', 'honey_block', 'sugar_from_honey_bottle', 'firework_rocket_simple', 'map_cloning', 'book_cloning', + 'oak_planks', 'stick', 'crafting_table', 'chest', 'torch', 'iron_block', 'iron_ingot_from_iron_block', + 'bread', 'tnt', 'white_banner', 'shield_decoration', 'armor_dye', 'repair_item', 'tipped_arrow', + 'suspicious_stew', 'decorated_pot', 'bundle', 'white_bed', 'red_dye_from_poppy', 'mushroom_stew', + 'pumpkin_pie', 'rabbit_stew_from_brown_mushroom', 'beacon', 'oak_boat', 'dye_red_wool'] +JUNK = ['dirt', 'stone', 'diamond', 'stick', 'oak_planks', 'apple', 'feather', 'gold_nugget', 'bone', 'iron_ingot'] + + +def item(name, count=1, extra=''): + return '{id:"minecraft:%s",count:%d%s}' % (name, count, extra) + + +class Recipes: + """Shaped and shapeless crafting recipes of the datapack, with item tags resolved.""" + + def __init__(self, resources): + root = resources / 'data/minecraft' + self.recipes = {} + for path in sorted((root / 'recipe').glob('*.json')): + self.recipes[path.stem] = json.loads(path.read_text()) + self.tag_dir = root / 'tags/item' + self.tags = {} + + def tag(self, name): + if name not in self.tags: + path = self.tag_dir / (name.split(':')[1] + '.json') + out = [] + for v in json.loads(path.read_text())['values'] if path.exists() else []: + v = v['id'] if isinstance(v, dict) else v + out.extend(self.tag(v[1:]) if v.startswith('#') else [v]) + self.tags[name] = out + return self.tags[name] + + def choices(self, ingredient): + if isinstance(ingredient, list): + out = [] + for i in ingredient: + out.extend(self.choices(i)) + return out + if isinstance(ingredient, dict): + ingredient = ingredient.get('item') or ('#' + ingredient['tag']) + return self.tag(ingredient[1:]) if ingredient.startswith('#') else [ingredient] + + def grid(self, rng, name): + """The nine cells of one way to fill the recipe, or None for specials without a pattern.""" + r = self.recipes.get(name) + if r is None: + return None + cells = [None] * 9 + if r['type'] == 'minecraft:crafting_shaped': + pattern = r['pattern'] + if len(pattern) > 3 or any(len(row) > 3 for row in pattern): + return None + dx = rng.randrange(0, 4 - max(len(row) for row in pattern)) + dy = rng.randrange(0, 4 - len(pattern)) + for y, row in enumerate(pattern): + for x, ch in enumerate(row): + if ch != ' ': + cells[(y + dy) * 3 + x + dx] = rng.choice(self.choices(r['key'][ch])).split(':')[1] + elif r['type'] == 'minecraft:crafting_shapeless': + ingredients = r['ingredients'] + if len(ingredients) > 9: + return None + for at, ing in zip(rng.sample(range(9), len(ingredients)), ingredients): + cells[at] = rng.choice(self.choices(ing)).split(':')[1] + elif r['type'] == 'minecraft:crafting_transmute': + at = rng.sample(range(9), 2) + cells[at[0]] = rng.choice(self.choices(r['input'])).split(':')[1] + cells[at[1]] = rng.choice(self.choices(r['material'])).split(':')[1] + else: + return None + return cells + + +SPECIAL = { + 'firework_rocket_simple': lambda rng: ['paper', 'gunpowder'] + ['gunpowder'] * rng.randrange(0, 3), + 'map_cloning': lambda rng: ['filled_map', 'map'], + 'book_cloning': lambda rng: ['written_book', 'writable_book'], + 'armor_dye': lambda rng: ['leather_helmet', rng.choice(['red_dye', 'blue_dye', 'white_dye'])], + 'repair_item': lambda rng: ['iron_pickaxe', 'iron_pickaxe'], + 'shield_decoration': lambda rng: ['shield', 'red_banner'], + 'suspicious_stew': lambda rng: ['bowl', 'red_mushroom', 'brown_mushroom', 'poppy'], + 'tipped_arrow': lambda rng: None, +} + + +def fill_special(rng, name): + make = SPECIAL.get(name) + items = make(rng) if make else None + if not items: + return None + cells = [None] * 9 + for at, it in zip(rng.sample(range(9), len(items)), items): + cells[at] = it + return cells + + +def stack_of(name, count, rng): + extra = '' + if name in ('iron_pickaxe',): + extra = ',components:{"minecraft:damage":%d}' % rng.randrange(1, 200) + if name == 'written_book': + extra = ',components:{"minecraft:written_book_content":{title:{raw:"t"},author:"a",generation:0}}' + if name == 'filled_map': + extra = ',components:{"minecraft:map_id":%d}' % rng.randrange(0, 5) + return item(name, count, extra) + + +def counts(rng, name, items): + top = items.get('minecraft:' + name, {}).get('minecraft:max_stack_size', 64) + if top == 1: + return 1 + return min(top, rng.choice([1, 1, 1, 2, 3, 5, top])) + + +def cases(facts, items, recipes, count, seed): + rng = random.Random(seed) + states = d.States(facts) + names = [n for n in recipes.recipes if recipes.recipes[n]['type'] in + ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless', 'minecraft:crafting_transmute')] + for n in range(count): + orientation = rng.choice(FRONTS) + front_dir = orientation.split('_')[0] + triggered = rng.random() < 0.9 + crafting = rng.random() < 0.2 + cells = [[0, 0, 0, states.get('crafter', orientation=orientation, triggered=str(triggered).lower(), + crafting=str(crafting).lower())]] + roll = rng.random() + if roll < 0.45: + name = rng.choice(names) + elif roll < 0.75: + name = rng.choice(FAVOURITES) + else: + name = None + grid = None + if name: + grid = recipes.grid(rng, name) or fill_special(rng, name) + if grid is None: + grid = [rng.choice(JUNK) if rng.random() < 0.4 else None for _ in range(9)] + if rng.random() < 0.1: + # A stray item that spoils the recipe. + grid[rng.randrange(9)] = rng.choice(JUNK) + stacks = [] + for slot, cell in enumerate(grid): + if cell: + stacks.append([0, 0, 0, slot, stack_of(cell, counts(rng, cell, items), rng)]) + disabled = [] + empty = [i for i in range(9) if not grid[i]] + for i in rng.sample(empty, rng.randrange(0, len(empty) + 1)) if empty and rng.random() < 0.4 else []: + disabled.append([0, 0, 0, i]) + if rng.random() < 0.1 and stacks: + # Disabling a filled slot does nothing. + disabled.append([0, 0, 0, rng.choice(stacks)[3]]) + dx, dy, dz = STEP[front_dir] + front = (dx, dy, dz) + block = rng.choice(FRONT_BLOCKS) + if block == 'crafter': + h.put(cells, front, states.get('crafter', orientation=rng.choice(FRONTS), triggered='false', crafting='false')) + for i in range(9): + roll = rng.random() + if roll < 0.35: + stacks.append([dx, dy, dz, i, item(rng.choice(['oak_planks', 'stick', 'cake', 'bucket', 'glass_bottle', 'stone']), + rng.choice([1, 1, 2, 63, 64]))]) + elif roll < 0.5: + disabled.append([dx, dy, dz, i]) + elif block in ('chest', 'trapped_chest', 'furnace', 'blast_furnace', 'smoker', 'dropper', 'dispenser', 'hopper', 'barrel', 'brewing_stand'): + props = {} + if block in ('chest', 'trapped_chest', 'furnace', 'blast_furnace', 'smoker'): + props['facing'] = rng.choice(['north', 'south', 'west', 'east']) + h.put(cells, front, states.get(block, **props)) + size = {'hopper': 5, 'dropper': 9, 'dispenser': 9, 'furnace': 3, 'blast_furnace': 3, 'smoker': 3, 'brewing_stand': 5}.get(block, 27) + fill = rng.choice([0, 0, 0.3, 0.95, 1.0]) + for i in range(size): + if rng.random() < fill: + stacks.append([dx, dy, dz, i, item(rng.choice(['stone', 'oak_planks', 'cake', 'stick', 'bucket', 'diamond']), + rng.choice([1, 16, 63, 64, 64]))]) + elif block == 'shulker_box': + h.put(cells, front, states.get('shulker_box', facing=front_dir)) + elif block != 'air': + h.put(cells, front, states.get(block)) + case = {**h.environment(rng), 'mode': 'craft', 'pos': [0, 0, 0], 'cells': cells, 'items': stacks, + 'disabled': disabled, 'ticks': rng.choice([0, 0, 1, 3, 5, 6, 7, 9])} + case.pop('raining', None) + case.pop('thundering', None) + yield case + + +def main(): + parser = h.argument_parser(__doc__) + args = parser.parse_args() + if args.count == 40000: + args.count = 4000 + lock, jars, libraries = base.verify_artifacts() + facts = h.load_facts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + items = json.loads((resources / 'items.json').read_text()) + recipes = Recipes(resources) + work = lab.LOCAL / 'crafter-parity' + work.mkdir(parents=True, exist_ok=True) + all_cases = list(cases(facts, items, recipes, args.count, args.seed)) + (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases)) + classes = work / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + java_root = lab.ROOT / 'mods/horizon/src/test/java' + d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn', + '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) + d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', + str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) + d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) + d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) + native = h.split_cases((work / 'native.txt').read_text(), ignore) + rust = h.split_cases((work / 'rust.txt').read_text(), ignore) + assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) + groups, errors = {}, {} + for case, a, b in zip(all_cases, native, rust): + if a and a[0].startswith('error'): + errors.setdefault(a[0], []).append(case) + continue + if not d.same(a, b): + grid = sorted({i[4].split('"')[1] for i in case['items'] if i[:3] == [0, 0, 0]}) + front = [facts.describe(c[3]).split('[')[0] for c in case['cells'][1:2]] or ['air'] + groups.setdefault(f'{front[0]} <- {",".join(grid) or "empty"}', []).append((case, a, b)) + for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])): + print(f'oracle error x{len(entries)}: {kind}') + 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[:args.show]: + print(' case ' + d.describe(case, facts) + ' disabled=' + json.dumps(case['disabled']) + f' ticks={case["ticks"]}') + print(' native ' + ' | '.join(sorted(a))) + print(' rust ' + ' | '.join(sorted(b))) + total = sum(len(v) for v in groups.values()) + skipped = sum(len(v) for v in errors.values()) + print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors)') + h.finish(total + skipped) + + +if __name__ == '__main__': + main() From eb9bee05bd284335e5d6fd2254155713317deb05 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:31:00 +0200 Subject: [PATCH 2/7] Run the loom and the crafter menu on the verified menu engine LoomMenu (selectable patterns, clickMenuButton, the six-layer limit, quick moves, the result's onTake) and the server's CrafterMenu over the block entity (the result following the grid, slot state packets, filled disabled slots enabling) join the menu click harness, now 8,000 click sequences over 19 menus with pattern button and slot state ops. Slot clicks end with setChanged and container slots are limited to their stack size as SimpleContainer does. The game's loom and crafter screens now click through Game::menu_session on the same engine. Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 3 + .../horizon-client/examples/menu_fixture.rs | 20 ++ crates/horizon-client/src/game.rs | 281 ++++++++++++------ crates/horizon-client/src/game/loom.rs | 179 ++++------- .../src/game/machines/crafter.rs | 101 ++++--- crates/horizon-client/src/game/stations.rs | 23 +- crates/horizon-client/src/menu.rs | 266 ++++++++++++++++- .../horizonlab/parity/VanillaMenuOracle.java | 32 +- tools/test_menu_click_parity.py | 78 ++++- 9 files changed, 698 insertions(+), 285 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index f2cd257cd..7de043b11 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -80,10 +80,13 @@ fn main() -> horizon_client::Result<()> { let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); + // The inventory menu never reads banner patterns. + 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 in input.lines() { diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 0909d3de4..0d1d496ed 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -35,10 +35,12 @@ fn main() -> horizon_client::Result<()> { 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::load(root); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, + banners: &banners, }; let mut out = String::new(); for line in input.lines() { @@ -50,6 +52,7 @@ fn main() -> horizon_client::Result<()> { menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); } menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + menu.settle(&env); for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { menu.data[i] = v.as_i64().unwrap_or(0) as i32; } @@ -58,6 +61,23 @@ fn main() -> horizon_client::Result<()> { 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; + match op[2].as_str().unwrap_or_default() { + // ServerboundContainerButtonClickPacket: clickMenuButton. + "BUTTON" => { + menu.button(&env, slot); + out += &format!("{}\n", state(&menu)); + continue; + } + // ServerboundContainerSlotStateChangedPacket. + "SLOT_STATE" => { + if (0..9).contains(&slot) { + menu.set_slot_state(slot as usize, button == 1); + } + out += &format!("{}\n", state(&menu)); + continue; + } + _ => {} + } 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)), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..8fd558374 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3528,6 +3528,50 @@ impl Game<'_> { } /// 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::Input; + if let [(Some(slot), button, input)] = ops { + self.crafter_slot_clicked(*slot, *button, *input); + } + let ops = ops.to_vec(); + self.menu_session(move |menu, env, to_menu| { + let mut clicks = Vec::new(); + for &(slot, button, input) in &ops { + let menu_slot = match slot { + Some(g) => { + if g == 200 && input != Input::QuickMove { + return None; + } + match to_menu(g) { + Some(i) => i as i32, + None => return None, + } + } + None => -999, + }; + clicks.push((menu_slot, button, input)); + } + for (menu_slot, button, input) in clicks { + if menu.click(env, menu_slot, button, input).is_err() { + // Vanilla's server throws: nothing of this click is kept. + return Some(false); + } + } + Some(true) + }) + } + /// The open menu as the verified engine (`horizon_client::menu`): the + /// game's slots are copied in, `run` acts on it, and the slots, carried + /// stack, menu data and drops are copied back when it returns Some(true) + /// (Some(false): handled, nothing kept; None: not handled). False when the + /// open screen is not one the engine models or `run` did not handle it. + pub(super) fn menu_session( + &mut self, + run: impl FnOnce( + &mut horizon_client::menu::Menu, + &horizon_client::menu::Env, + &dyn Fn(usize) -> Option, + ) -> Option, + ) -> bool { use horizon_client::menu::{Env, Kind, Menu}; #[derive(Clone, Copy)] struct Map { @@ -3586,107 +3630,145 @@ impl Game<'_> { } } } - 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, - ) + // Menu slot -> game slot, for every menu slot. + let mut plain_map = None; + let crafter_open = matches!(self.container_kind(), Some(BlockEntity::Crafter(_))); + let loom_open = self + .station + .as_ref() + .is_some_and(|s| s.kind == stations::Kind::Loom); + let (kind, game_of): (Kind, Vec>) = if crafter_open { + // CrafterMenu: the grid, the inventory, then the result. + let mut v: Vec> = (300..309).map(Some).collect(); + v.extend((9..36).chain(0..9).map(Some)); + v.push(None); + (Kind::CrafterBlock, v) + } else if loom_open { + // LoomMenu: banner, dye, pattern, result, then the inventory. + let mut v: Vec> = (0..3).map(|i| Some(stations::INPUT + i)).collect(); + v.push(Some(stations::RESULT)); + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Loom, v) } else { - 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; + 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) } - match map.to_menu(g) { - Some(i) => i as i32, - None => return false, - } - } - None => -999, + 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 { + return false; }; - clicks.push((menu_slot, button, input)); - } + let total = Menu::new(kind).slot_count(); + plain_map = Some(map); + (kind, (0..total).map(|i| map.to_game(i)).collect()) + }; + // The plain map also takes the crafting result slot (a shift-click on it). + let to_menu = |g: usize| match plain_map { + Some(map) => map.to_menu(g), + None => game_of.iter().position(|x| *x == Some(g)), + }; 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())) + let before: Vec> = game_of + .iter() + .map(|g| g.and_then(|g| self.slot_mut(g).clone())) .collect(); 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()); - } - menu.carried = carried; - for (menu_slot, button, input) in clicks { - if menu.click(&env, menu_slot, button, input).is_err() { - return true; - } - } + let station_menu = self.station.as_ref().map(|s| { ( - (0..total).map(|i| menu.slot(i).cloned()).collect(), - menu.carried.take(), - std::mem::take(&mut menu.dropped), + s.loom.selected.map_or(-1, |i| i as i32), + s.loom.patterns.clone(), ) + }); + let crafter_data = match self.container_kind() { + Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), + _ => None, }; + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + banners: &self.res.stations.banners, + }; + menu.creative = creative; + for (i, stack) in before.iter().enumerate() { + menu.set_slot(&env, i, stack.clone()); + } + menu.settle(&env); + if kind == Kind::Loom + && let Some((selected, patterns)) = station_menu + { + // The menu's state between clicks: what set_slot recomputed is replaced. + menu.data[0] = selected; + menu.loom_patterns = patterns; + menu.set_slot(&env, 3, before[3].clone()); + } + if let Some((disabled, triggered)) = crafter_data { + for (i, d) in disabled.iter().enumerate() { + menu.data[i] = i32::from(*d); + } + menu.data[9] = i32::from(triggered); + } + menu.carried = carried; + menu.drops.clear(); + match run(&mut menu, &env, &to_menu) { + None => return false, + Some(false) => return true, + Some(true) => {} + } + let after: Vec> = (0..total).map(|i| menu.slot(i).cloned()).collect(); + let carried = menu.carried.take(); + let dropped = std::mem::take(&mut menu.dropped); + let sounds = std::mem::take(&mut menu.sounds); for (i, stack) in after.into_iter().enumerate() { - if let Some(g) = map.to_game(i) { + if let Some(g) = game_of[i] { *self.slot_mut(g) = stack; } } @@ -3694,6 +3776,25 @@ impl Game<'_> { for stack in dropped { self.player_drop(stack); } + if kind == Kind::Loom { + if let Some(s) = self.station.as_mut() { + s.loom.selected = usize::try_from(menu.data[0]).ok(); + s.loom.patterns = std::mem::take(&mut menu.loom_patterns); + } + for sound in sounds { + self.loom_sound(sound); + } + self.loom_screen_changed(); + } + if kind == Kind::CrafterBlock + && let Some(BlockEntity::Crafter(c)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + for (i, d) in c.disabled.iter_mut().enumerate() { + *d = menu.data[i] == 1; + } + } if matches!(kind, Kind::Furnace(_)) && let Some(BlockEntity::Furnace(f)) = self .container @@ -3849,7 +3950,7 @@ impl Game<'_> { }; let held_shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); - if self.crafter_click(slot, held_shift) { + if self.crafter_click(slot, held_shift, right) { return; } if held_shift && self.container.is_some() && self.container_quick_move(slot) { diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 39663c298..561713d8a 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -1,10 +1,8 @@ -//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a -//! banner with a dye (and a pattern item for the special patterns), the -//! six-layer limit, the scrolling pattern list and the banner preview. -use super::{ - Game, - stations::{INPUT, Station}, -}; +//! The loom screen (`LoomScreen`): the scrolling pattern list, the banner +//! preview and the six-layer error. The menu itself (`LoomMenu`: slots, +//! selectable patterns, the pattern buttons, quick moves, the result) runs on +//! the verified engine, `horizon_client::menu`, through `Game::menu_session`. +use super::{Game, stations::Kind}; use horizon_client::{ banner::{self, BannerLayer}, hud::{HudBatch, Rect, rgba}, @@ -24,6 +22,8 @@ pub(super) struct LoomState { pub(super) scroll: f32, pub(super) start_row: usize, pub(super) scrolling: bool, + /// The inputs the screen last saw (`bannerStack`, `dyeStack`, `patternStack`). + last_inputs: [Option; 3], } impl LoomState { fn total_rows(&self) -> usize { @@ -65,138 +65,77 @@ pub(super) fn dye_color(name: &str) -> u32 { } impl Game<'_> { - /// `LoomMenu.slotsChanged` and the screen's `containerChanged`. - pub(super) fn loom_changed(&self, s: &mut Station) { - let banners = &self.res.stations.banners; - let items = &self.res.items; - let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref()); + /// `LoomScreen.containerChanged`: the error flag, whether the pattern + /// buttons show (only when an input changed), and the scroller reset. + pub(super) fn loom_screen_changed(&mut self) { + let Some(s) = self.station.as_mut().filter(|s| s.kind == Kind::Loom) else { + return; + }; + let inputs = [ + s.inputs[0].clone(), + s.inputs[1].clone(), + s.inputs[2].clone(), + ]; let l = &mut s.loom; - let mut result = None; - if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) { - let valid = l.selected.is_some_and(|i| i < l.patterns.len()); - let previous = std::mem::take(&mut l.patterns); - l.patterns = banners.selectable(s.inputs[2].as_ref()); - let shown = if l.patterns.len() == 1 { - l.selected = Some(0); - Some(l.patterns[0].clone()) - } else if !valid { - l.selected = None; - None - } else { - let value = previous[l.selected.unwrap_or(0)].clone(); - match l.patterns.iter().position(|p| *p == value) { - Some(i) => { - l.selected = Some(i); - Some(value) - } - None => { - l.selected = None; - None - } - } - }; - l.has_max = banner::has_max_layers(banner_stack); - if let Some(pattern) = shown { - if l.has_max { - l.selected = None; - } else if let Some(dye) = banners.loom_dye(items, dye_stack) { - result = Some(banner::loom_result(banner_stack, &dye, &pattern)); - } - } - l.display = !l.has_max && !l.patterns.is_empty(); - } else { - l.patterns.clear(); - l.selected = None; - l.has_max = banner_in.is_some_and(banner::has_max_layers); - l.display = false; + l.has_max = inputs[0].as_ref().is_some_and(banner::has_max_layers); + if inputs != l.last_inputs { + l.display = + inputs[0].is_some() && inputs[1].is_some() && !l.has_max && !l.patterns.is_empty(); } if l.start_row >= l.total_rows() { l.start_row = 0; l.scroll = 0.0; } - s.result = result; + l.last_inputs = inputs; } - /// The loom slots' `mayPlace`. - pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) { - let banners = &self.res.stations.banners; - let ok = match input { - 0 => stack.item.ends_with("_banner"), - 1 => banners.loom_dye(&self.res.items, stack).is_some(), - _ => banners.is_pattern_item(&self.res.items, stack), + /// A sound the loom menu played: the result's once per tick. + pub(super) fn loom_sound(&mut self, sound: &str) { + let ticks = self.ticks; + let Some(s) = self.station.as_mut() else { + return; }; - (ok, 64) + if s.last_sound == ticks { + return; + } + s.last_sound = ticks; + let pos = s.pos; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play(sound, Some(at), 1.0, 1.0); } - /// The result slot's `onTake`: one banner and one dye are used up. - pub(super) fn loom_taken(&mut self, s: &mut Station) { - for slot in &mut s.inputs[..2] { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - if s.inputs[0].is_none() || s.inputs[1].is_none() { - s.loom.selected = None; - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - let pos = s.pos; - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; + /// `LoomScreen.mouseClicked` on a pattern button: `clickMenuButton`, and + /// the select sound when the menu took it. + fn loom_button(&mut self, index: usize) -> bool { + let mut taken = false; + let flag = &mut taken; + self.menu_session(|menu, env, _| { + *flag = menu.button(env, index as i32); + Some(*flag) + }); + if taken { self.audio - .play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0); - } - } - /// `LoomMenu.quickMoveStack` from an inventory slot. - pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool { - let banners = &self.res.stations.banners; - let items = &self.res.items; - let target = if stack.item.ends_with("_banner") { - Some(INPUT) - } else if banners.loom_dye(items, stack).is_some() { - Some(INPUT + 1) - } else if banners.is_pattern_item(items, stack) { - Some(INPUT + 2) - } else { - None - }; - match target { - Some(t) => self.move_to(stack, &[t], false), - None if (9..36).contains(&slot) => { - let hotbar: Vec = (0..9).collect(); - self.move_to(stack, &hotbar, false) - } - None if slot < 9 => { - let main: Vec = (9..36).collect(); - self.move_to(stack, &main, false) - } - None => false, + .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); } + taken } /// A left click inside the loom's pattern grid or scroller. pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool { - let Some(s) = self.station.as_ref() else { + let Some(start_row) = self + .station + .as_ref() + .filter(|s| s.loom.display) + .map(|s| s.loom.start_row) + else { return false; }; - let l = &s.loom; - if !l.display { - return false; - } for row in 0..4 { for column in 0..4 { - let index = (row + l.start_row) * 4 + column; + let index = (row + start_row) * 4 + column; let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); - if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) { - if let Some(s) = self.station.as_mut() { - s.loom.selected = Some(index); - } - self.audio - .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); - self.station_changed(); + if inside(local, x, y, BUTTON, BUTTON) && self.loom_button(index) { return true; } } diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index ea795fe35..32b28ad70 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -291,64 +291,67 @@ impl Game<'_> { (self.carried.is_none() && c.items[i].is_none() && !c.disabled[i] && !self.spectator()) .then(|| self.translate("gui.togglable_slot", "Click to disable slot")) } - /// A click in the crafter menu before the generic handling; true when - /// it was fully handled (the result, shift-clicks). - pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool) -> bool { + /// A click in the crafter menu: `CrafterMenu` on the verified menu engine. + pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool, right: bool) -> bool { if !self.crafter_open() { return false; } - if slot == RESULT_SLOT { - return true; - } - if (300..309).contains(&slot) { - // CrafterScreen.slotClicked: toggle an empty slot. - let i = slot - 300; - if !shift && !self.spectator() && self.slot_mut(slot).is_none() { - let carried_empty = self.carried.is_none(); - let key = self.container; - let mut toggled = None; - if let Some(BlockEntity::Crafter(c)) = - key.and_then(|k| self.world.block_entities.get_mut(&k)) - { - if c.disabled[i] { - c.set_slot_state(i, true); - toggled = Some(true); - } else if carried_empty { - c.set_slot_state(i, false); - toggled = Some(false); - } - } - if let Some(enabled) = toggled { - let pitch = if enabled { 1.0 } else { 0.75 }; - self.audio - .play("minecraft:ui.button.click", None, 0.4, pitch); - } - } - } - if shift { - self.crafter_quick_move(slot); - return true; - } - false + let input = if shift { + horizon_client::menu::Input::QuickMove + } else { + horizon_client::menu::Input::Pickup + }; + self.menu_click(Some(slot), i32::from(right), input); + true } - /// `CrafterMenu.quickMoveStack`. - fn crafter_quick_move(&mut self, slot: usize) { - if slot >= 309 { + /// `CrafterScreen.slotClicked`: an empty grid slot is enabled by a click + /// (or a number key with a hotbar item) when disabled, and disabled by a + /// click with nothing carried; the menu then gets the click itself. + pub(in crate::game) fn crafter_slot_clicked( + &mut self, + slot: usize, + button: i32, + input: horizon_client::menu::Input, + ) { + use horizon_client::menu::Input; + if !self.crafter_open() || !(300..309).contains(&slot) || self.spectator() { return; } - let Some(mut stack) = self.slot_mut(slot).take() else { + let i = slot - 300; + let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else { return; }; - if slot >= 300 { - let player: Vec = (9..36).chain(0..9).collect(); - self.move_to(&mut stack, &player, true); - } else { - let grid: Vec = (300..309).collect(); - self.move_to(&mut stack, &grid, false); - } - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); + if c.items[i].is_some() { + return; } + let disabled = c.disabled[i]; + let enable = match input { + Input::Pickup if disabled => Some(true), + Input::Pickup if self.carried.is_none() => Some(false), + Input::Swap if disabled => usize::try_from(button) + .ok() + .and_then(|b| { + if b == 40 { + Some(&self.offhand) + } else { + self.inventory.get(b) + } + }) + .is_some_and(Option::is_some) + .then_some(true), + _ => None, + }; + let Some(enabled) = enable else { + return; + }; + // ServerboundContainerSlotStateChangedPacket: CrafterBlockEntity.setSlotState. + self.menu_session(|menu, _, _| { + menu.set_slot_state(i, enabled); + Some(true) + }); + let pitch = if enabled { 1.0 } else { 0.75 }; + self.audio + .play("minecraft:ui.button.click", None, 0.4, pitch); } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index e75db5b6f..a06ed2a9c 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -447,7 +447,8 @@ impl Game<'_> { Kind::Merchant => super::trading::update(&mut s, items), Kind::Beacon => {} Kind::Cartography => s.result = self.cartography_result(&s), - Kind::Loom => self.loom_changed(&mut s), + // The menu engine keeps the loom's state (Game::menu_session). + Kind::Loom => {} Kind::Stonecutter => { let item = s.inputs[0].as_ref().map(|i| i.item.clone()); if item != s.input_item { @@ -522,7 +523,7 @@ impl Game<'_> { match s.kind { Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), - Kind::Loom => self.loom_slot_rules(i, stack), + Kind::Loom => (false, 64), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), Kind::Cartography => ( matches!( @@ -644,12 +645,8 @@ impl Game<'_> { return false; }; let player = Self::player_slots(); - let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom); let moved = if (300..305).contains(&slot) || slot >= INPUT { - // LoomMenu moves into the inventory front to back, the others back to front. - self.move_to(&mut stack, &player, !loom) - } else if loom { - self.loom_quick_move(slot, &mut stack) + self.move_to(&mut stack, &player, true) } else if self.brewing_open() { // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. let data = self.data(); @@ -894,7 +891,7 @@ impl Game<'_> { self.cartography_taken(pos); } } - Kind::Loom => self.loom_taken(&mut s), + Kind::Loom => {} Kind::Enchanting => {} } self.station = Some(s); @@ -1069,6 +1066,16 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; + if self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom) { + // LoomMenu clicks run on the verified menu engine. + let input = if shift { + horizon_client::menu::Input::QuickMove + } else { + horizon_client::menu::Input::Pickup + }; + self.menu_click(Some(slot), i32::from(right), input); + return true; + } if slot == RESULT { self.click_result(shift); return true; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 4ced9e6d0..149e34cc0 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -1,20 +1,25 @@ //! `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. +//! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing +//! stand, the crafter (its client menu and the block entity's server menu with +//! `setSlotState`) and the loom (`clickMenuButton`, `slotsChanged`). //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. use crate::{ + banner::{self, Banners}, brewing::Brewing, crafting::Recipes, items::{ItemStack, Items}, }; +use std::sync::Arc; /// What a menu needs to know about items and recipes. pub struct Env<'a> { pub items: &'a Items, pub recipes: &'a Recipes, pub brewing: &'a Brewing, + pub banners: &'a Banners, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -54,7 +59,12 @@ pub enum Kind { /// The cooking recipe type: smelting, blasting or smoking. Furnace(&'static str), Brewing, + /// `CrafterMenu` over a plain crafting container (the client's menu). Crafter, + /// `CrafterMenu` over the `CrafterBlockEntity` (the server's menu): the + /// result follows the grid, and filling a disabled slot enables it. + CrafterBlock, + Loom, } impl Kind { @@ -73,6 +83,8 @@ impl Kind { "smoker" => Self::Furnace("smoking"), "brewing" => Self::Brewing, "crafter" => Self::Crafter, + "crafter_be" => Self::CrafterBlock, + "loom" => Self::Loom, _ => return None, }) } @@ -100,6 +112,12 @@ enum Role { Ingredient, /// `BrewingStandMenu.FuelSlot`. BrewFuel, + /// The loom's banner, dye and pattern slots. + LoomBanner, + LoomDye, + LoomPattern, + /// The loom's result slot (a plain slot whose `onTake` uses the inputs). + LoomResult, } #[derive(Clone, Copy)] @@ -133,6 +151,10 @@ pub struct Menu { quick_status: i32, quick_type: i32, quick_slots: Vec, + /// `LoomMenu.selectablePatterns`. + pub loom_patterns: Vec>, + /// Sounds the menu plays (`ui.loom.take_result`), for the caller. + pub sounds: Vec<&'static str>, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -238,7 +260,7 @@ impl Menu { slots.extend(main(27, Role::Shulker)); player(&mut slots); } - Kind::Crafter => { + Kind::Crafter | Kind::CrafterBlock => { containers[MAIN] = vec![None; 9]; slots.extend(main(9, Role::CrafterIn)); player(&mut slots); @@ -249,6 +271,26 @@ impl Menu { }); data = 10; } + Kind::Loom => { + containers[MAIN] = vec![None; 3]; + for (index, role) in [Role::LoomBanner, Role::LoomDye, Role::LoomPattern] + .into_iter() + .enumerate() + { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::LoomResult, + }); + player(&mut slots); + data = 1; + } Kind::Brewing => { containers[MAIN] = vec![None; 5]; for (index, role) in [ @@ -308,6 +350,125 @@ impl Menu { quick_status: 0, quick_type: 0, quick_slots: Vec::new(), + loom_patterns: Vec::new(), + sounds: Vec::new(), + } + } + + pub fn kind(&self) -> Kind { + self.kind + } + + /// `clickMenuButton`: the loom's pattern buttons. False when refused. + pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() { + return false; + } + self.data[0] = id; + let pattern = self.loom_patterns[id as usize].clone(); + self.loom_setup_result(env, &pattern); + true + } + + /// `CrafterBlockEntity.setSlotState` (the slot state packet): only an + /// empty slot can be disabled or enabled. + pub fn set_slot_state(&mut self, slot: usize, enabled: bool) { + if self.kind == Kind::CrafterBlock && slot < 9 && self.containers[MAIN][slot].is_none() { + self.data[slot] = i32::from(!enabled); + } + } + + /// The menu after a fixture set its slots: the block crafter's slot + /// listener has refreshed the result (`broadcastChanges`). + pub fn settle(&mut self, env: &Env) { + if self.kind == Kind::CrafterBlock { + self.crafter_result(env); + } + } + + /// `CrafterMenu.refreshRecipeResult`. + fn crafter_result(&mut self, env: &Env) { + self.containers[RESULT][0] = env + .recipes + .find(&self.containers[MAIN], 3) + .map(|(_, stack)| stack) + .filter(|s| s.count > 0); + } + + /// `LoomMenu.setupResultSlot`. + fn loom_setup_result(&mut self, env: &Env, pattern: &str) { + let mut result = None; + if let (Some(banner_stack), Some(dye)) = ( + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ) && let Some(color) = env.banners.loom_dye(env.items, dye) + { + result = Some(banner::loom_result(banner_stack, &color, pattern)); + } + self.containers[RESULT][0] = result; + } + + /// `LoomMenu.slotsChanged`. + fn loom_changed(&mut self, env: &Env) { + let has_inputs = self.containers[MAIN][0].is_some() && self.containers[MAIN][1].is_some(); + if !has_inputs { + self.containers[RESULT][0] = None; + self.loom_patterns.clear(); + self.data[0] = -1; + return; + } + let selected = self.data[0]; + let valid = selected >= 0 && (selected as usize) < self.loom_patterns.len(); + let pattern_item = self.containers[MAIN][2].clone(); + let previous = std::mem::replace( + &mut self.loom_patterns, + env.banners.selectable(pattern_item.as_ref()), + ); + let shown = if self.loom_patterns.len() == 1 { + self.data[0] = 0; + Some(self.loom_patterns[0].clone()) + } else if !valid { + self.data[0] = -1; + None + } else { + let value = previous[selected as usize].clone(); + match self.loom_patterns.iter().position(|p| *p == value) { + Some(i) => { + self.data[0] = i as i32; + Some(value) + } + None => { + self.data[0] = -1; + None + } + } + }; + match shown { + Some(pattern) => { + let full = self.containers[MAIN][0] + .as_ref() + .is_some_and(banner::has_max_layers); + if full { + self.data[0] = -1; + self.containers[RESULT][0] = None; + } else { + self.loom_setup_result(env, &pattern); + } + } + None => self.containers[RESULT][0] = None, + } + } + + /// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs, + /// the block crafter refreshes its result. + fn slot_changed(&mut self, env: &Env, s: usize) { + if self.slots[s].container != MAIN { + return; + } + match self.kind { + Kind::Loom => self.loom_changed(env), + Kind::CrafterBlock => self.crafter_result(env), + _ => {} } } @@ -414,9 +575,18 @@ impl Menu { .items .get(&stack.item) .is_some_and(|i| i.brewing_fuel.is_some()), + Role::LoomBanner => Self::is_banner(stack), + Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), + Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), + Role::LoomResult => false, } } + /// `BannerItem`. + fn is_banner(stack: &ItemStack) -> bool { + stack.item.ends_with("_banner") + } + fn may_pickup(&self, s: usize) -> bool { match self.slots[s].role { Role::Inert => false, @@ -444,16 +614,34 @@ impl Menu { fn put(&mut self, env: &Env, s: usize, mut stack: Option) { tidy(&mut stack); let slot = self.slots[s]; + // SimpleContainer / BaseContainerBlockEntity.setItem: limitSize to + // getMaxStackSize(stack). The loom's result is a SimpleContainer too. + if (slot.container == MAIN || slot.role == Role::LoomResult) + && let Some(st) = stack.as_mut() + { + st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st))); + } + // CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it. + if self.kind == Kind::CrafterBlock + && slot.container == MAIN + && self.data[slot.index] == 1 + && self.containers[MAIN][slot.index].is_none() + { + self.data[slot.index] = 0; + } self.containers[slot.container][slot.index] = stack; if slot.container == GRID { self.recompute(env); } + self.slot_changed(env, s); } /// `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 { + // ResultContainer.removeItem takes the whole stack; the loom's result + // is a SimpleContainer slot and splits. + if slot.container == RESULT && slot.role != Role::LoomResult { return self.containers[RESULT][0].take(); } let cell = &mut self.containers[slot.container][slot.index]; @@ -465,6 +653,10 @@ impl Menu { if out.is_some() && slot.container == GRID { self.recompute(env); } + // SimpleContainer.removeItem calls setChanged when it took something. + if out.is_some() && self.kind == Kind::Loom { + self.slot_changed(env, s); + } out } @@ -482,6 +674,21 @@ impl Menu { /// `ResultSlot.onTake` and the other `Slot.onTake` overrides. fn on_take(&mut self, env: &Env, s: usize) { + if self.slots[s].role == Role::LoomResult { + // LoomMenu's result onTake: one banner and one dye are used up. + self.remove(env, 0, 1); + self.remove(env, 1, 1); + if self.containers[MAIN][0].is_none() || self.containers[MAIN][1].is_none() { + self.data[0] = -1; + } + self.sounds.push("minecraft:ui.loom.take_result"); + return; + } + if matches!(self.kind, Kind::CrafterBlock) && self.slots[s].container == MAIN { + // Slot.onTake -> CrafterSlot.setChanged -> the result refresh. + self.slot_changed(env, s); + return; + } if self.slots[s].role != Role::CraftResult { return; } @@ -738,10 +945,12 @@ impl Menu { stack.count = 0; target.count = total; changed = true; + self.slot_changed(env, dest); } else if target.count < max { stack.count -= max - target.count; target.count = max; changed = true; + self.slot_changed(env, dest); } } } @@ -859,7 +1068,44 @@ impl Menu { return None; } } - Kind::Crafter => { + Kind::Loom => { + after_take = true; + if index == 3 { + if !self.move_to(env, &mut stack, 4, 40, true) { + return None; + } + } else if index > 3 { + let target = if Self::is_banner(&stack) { + Some(0) + } else if env.banners.loom_dye(env.items, &stack).is_some() { + Some(1) + } else if env.banners.is_pattern_item(env.items, &stack) { + Some(2) + } else { + None + }; + match target { + Some(t) => { + if !self.move_to(env, &mut stack, t, t + 1, false) { + return None; + } + } + None if index < 31 => { + if !self.move_to(env, &mut stack, 31, 40, false) { + return None; + } + } + None => { + if index < 40 && !self.move_to(env, &mut stack, 4, 31, false) { + return None; + } + } + } + } else if !self.move_to(env, &mut stack, 4, 40, false) { + return None; + } + } + Kind::Crafter | Kind::CrafterBlock => { after_take = true; if index < 9 { if !self.move_to(env, &mut stack, 9, 45, true) { @@ -961,9 +1207,11 @@ impl Menu { // The stack was edited in place in its slot. let slot = self.slots[index]; if stack.count == 0 { + self.containers[slot.container][slot.index] = None; self.put(env, index, None); } else { self.containers[slot.container][slot.index] = Some(stack.clone()); + self.slot_changed(env, index); } if check_count && stack.count == clicked.count { return None; @@ -1173,8 +1421,14 @@ impl Menu { Ok(()) } - /// The PICKUP branch of `doClick` (without the bundle overrides). + /// The PICKUP branch of `doClick` (without the bundle overrides), ending + /// with `slot.setChanged()`. fn pickup(&mut self, env: &Env, s: usize, primary: bool) { + self.pickup_inner(env, s, primary); + self.slot_changed(env, s); + } + + fn pickup_inner(&mut self, env: &Env, s: usize, primary: bool) { let clicked = self.slot(s).cloned(); match clicked { None => { @@ -1312,7 +1566,7 @@ impl Menu { if self.has_item(t) && self.quick_replace(t, &have, env) && self.may_pickup(t) - && self.slots[t].container != RESULT + && (self.slots[t].container != RESULT || self.kind == Kind::Loom) { let item = self.slot(t).expect("has item").clone(); if pass != 0 || item.count != Self::max_stack(env, &item) { 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 af5ca6e3c..f6d0c41ef 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -35,6 +35,8 @@ public final class VanillaMenuOracle { static java.lang.reflect.Method allocate; static RecipeManager recipes; static final List drops = new ArrayList<>(); + /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ + static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; @SuppressWarnings("unchecked") static T make(Class type) { @@ -131,6 +133,19 @@ public final class VanillaMenuOracle { case "smoker" -> new SmokerMenu(0, inv); case "brewing" -> new BrewingStandMenu(0, inv); case "crafter" -> new CrafterMenu(0, inv); + case "crafter_be" -> { + // The server's menu: the block entity is the container and its data. + crafter = new net.minecraft.world.level.block.entity.CrafterBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.CRAFTER.defaultBlockState()); + try { + Field data = net.minecraft.world.level.block.entity.CrafterBlockEntity.class.getDeclaredField("containerData"); + data.setAccessible(true); + yield new CrafterMenu(0, inv, crafter, (ContainerData) data.get(crafter)); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + case "loom" -> new LoomMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } @@ -180,6 +195,8 @@ public final class VanillaMenuOracle { 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())); + // The slot listener of the block crafter's menu refreshes the result. + if (f.get("menu").getAsString().equals("crafter_be")) menu.broadcastChanges(); var dataJson = f.getAsJsonArray("data"); for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); @@ -188,7 +205,20 @@ public final class VanillaMenuOracle { var op = opJson.getAsJsonArray(); int slot = op.get(0).getAsInt(); int button = op.get(1).getAsInt(); - var input = ContainerInput.valueOf(op.get(2).getAsString()); + String kind = op.get(2).getAsString(); + if (kind.equals("BUTTON")) { + // ServerGamePacketListenerImpl.handleContainerButtonClick + if (menu.clickMenuButton(player, slot)) menu.broadcastChanges(); + out.println(state(menu, inv)); + continue; + } + if (kind.equals("SLOT_STATE")) { + // handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState + if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1); + out.println(state(menu, inv)); + continue; + } + var input = ContainerInput.valueOf(kind); try { menu.clicked(slot, button, input, player); } catch (RuntimeException e) { diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 5137537b2..3a02efdb1 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -6,7 +6,9 @@ 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 +crafting table, chests, hopper, dispenser, shulker box, the furnaces, the +brewing stand, the crafter (the client's menu, and the server's over the block +entity with slot state packets) and the loom (with its pattern buttons). After every click the slots, carried stack, data slots and drops are compared. """ import argparse @@ -19,8 +21,13 @@ 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, 'crafter': 46} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10} + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, + 'crafter_be': 46, 'loom': 40} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1} +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] +PATTERNS = ['minecraft:' + p for p in ('base', 'square_bottom_left', 'stripe_bottom', 'cross', 'border', 'gradient', + 'creeper', 'flower', 'globe', 'rhombus', 'small_stripes', 'half_horizontal')] 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', @@ -69,8 +76,24 @@ class Gen: 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.""" + def loom_stack(self, roll=None): + """A banner (with up to seven layers), a dye, a pattern item or anything.""" + rng = self.rng + roll = rng.random() if roll is None else roll + if roll < 0.3: + layers = ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(PATTERNS), rng.choice(DYES)) + for _ in range(rng.choice([0, 0, 1, 2, 5, 6, 6, 7]))) + extra = ',components:{"minecraft:banner_patterns":[%s]}' % layers if layers else '' + return '{id:"minecraft:%s_banner",count:%d%s}' % (rng.choice(DYES), rng.choice([1, 1, 2, 16]), extra) + if roll < 0.55: + return snbt('minecraft:%s_dye' % rng.choice(DYES), rng.choice([1, 1, 2, 3, 64])) + if roll < 0.75: + pool = [k for k in self.items if k.endswith('_banner_pattern')] + return snbt(rng.choice(pool), 1) + return self.stack() + + def recipe(self, slots, width, start=1): + """Fills the crafting grid (slots `start`..) 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')], @@ -81,12 +104,23 @@ class Gen: 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) + slots[start + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1) - def ops(self, size): + def ops(self, size, menu=None): rng = self.rng out = [] for _ in range(rng.randrange(1, 9)): + if menu == 'loom' and rng.random() < 0.25: + # A pattern button (clickMenuButton), sometimes out of range. + out.append([rng.choice([0, 0, 1, 2, 3, 5, 10, 20, 39, 40, -1]), 0, 'BUTTON']) + continue + if menu == 'loom' and rng.random() < 0.15: + # The result: take it, shift it out, throw it. + out.append([3, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'THROW', 'SWAP'])]) + continue + if menu == 'crafter_be' and rng.random() < 0.2: + out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE']) + continue 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) @@ -113,8 +147,9 @@ class Gen: 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('--cases', type=int, default=8000) parser.add_argument('--limit', type=int, default=3) + parser.add_argument('--menus', help='comma-separated menus to run (default: all)') args = parser.parse_args() work = lib.work_dir('menu-click-parity') vanilla = lib.Vanilla(work) @@ -123,17 +158,38 @@ def main(): rng = random.Random(args.seed) g = Gen(rng, items) cases = [] + chosen = args.menus.split(',') if args.menus else list(MENUS) for n in range(args.cases): - menu = list(MENUS)[n % len(MENUS)] + menu = chosen[n % len(chosen)] size = MENUS[menu] slots = g.slots(size, rng.choice([0.1, 0.4, 0.8])) + if menu == 'loom': + for i in rng.sample(range(4, size), 8): + slots[i] = g.loom_stack() + # Mostly a banner, a dye and sometimes a pattern item in their slots. + slots[0] = g.loom_stack(0.0) if rng.random() < 0.75 else rng.choice(['-', g.loom_stack()]) + slots[1] = g.loom_stack(0.4) if rng.random() < 0.75 else rng.choice(['-', g.loom_stack()]) + slots[2] = g.loom_stack(0.6) if rng.random() < 0.4 else rng.choice(['-', '-', g.loom_stack()]) + # The result slot follows the inputs; a fixture stack there is rare. + slots[3] = '-' if rng.random() < 0.9 else g.loom_stack() + if menu == 'crafter_be': + slots[45] = '-' + if rng.random() < 0.6: + g.recipe(slots, 3, start=0) 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) + def datum(i): + if menu in ('crafter', 'crafter_be'): + return rng.choice([0, 0, 1]) + if menu == 'loom': + return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) + return 0 + carried = (g.loom_stack() if menu == 'loom' else g.stack()) if rng.random() < 0.5 else '-' cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, - '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)}) + 'carried': carried, 'data': [datum(i) for i in range(DATA.get(menu, 0))], + 'ops': g.ops(size, menu)}) (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') From acf4df3a907a5c50eed64bf8dee92258acb18059 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:51:38 +0200 Subject: [PATCH 3/7] Place recipe book recipes as vanilla's ServerPlaceRecipe does ServerPlaceRecipe and StackedContents' RecipePicker run on the menu engine (horizon_client::menu::place) for the inventory, crafting table and furnaces: testClearGrid, clearGrid with placeItemBackInInventory, the biggest craftable stack, clamping to stack sizes and moveItemToGrid. A new harness compares 6,000 placements with vanilla; vanilla's item order follows identity hash codes, so the oracle hands its order to the Rust side. The game's recipe book now places through the engine, and its craftable filter uses the same counts and placement ingredients. Co-Authored-By: Claude Opus 5.5 --- .../examples/place_recipe_fixture.rs | 89 +++ crates/horizon-client/src/crafting.rs | 185 +++-- crates/horizon-client/src/game.rs | 9 + crates/horizon-client/src/game/recipe_book.rs | 248 +----- crates/horizon-client/src/menu.rs | 20 +- crates/horizon-client/src/menu/place.rs | 706 ++++++++++++++++++ crates/horizon-client/src/recipe_book.rs | 188 +---- .../parity/VanillaPlaceRecipeOracle.java | 113 +++ tools/test_place_recipe_parity.py | 184 +++++ 9 files changed, 1308 insertions(+), 434 deletions(-) create mode 100644 crates/horizon-client/examples/place_recipe_fixture.rs create mode 100644 crates/horizon-client/src/menu/place.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlaceRecipeOracle.java create mode 100644 tools/test_place_recipe_parity.py 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() From 621fca874ce1aebf0e015aefc06704cff433f699 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:02:53 +0200 Subject: [PATCH 4/7] Keep the player's recipe book as vanilla's ServerRecipeBook does The known and highlighted recipes, the book settings and the saved recipeBook compound now live in one place (recipe_book::Settings with a RecipeIndex of learnability and display counts): advancement rewards, /recipe give and take (counting displays, never special recipes) and crafting a recipe award through it, and loading drops unknown recipes instead of rebuilding the set from done advancements. A new harness compares 1,500 operation sequences with vanilla's ServerRecipeBook and its codec. Co-Authored-By: Claude Opus 5.5 --- .../examples/recipe_book_fixture.rs | 143 ++++++++++++++++ crates/horizon-client/src/game.rs | 16 +- .../horizon-client/src/game/advancements.rs | 47 +++--- .../src/game/commands/world_cmds.rs | 44 ++--- crates/horizon-client/src/game/recipe_book.rs | 13 +- crates/horizon-client/src/menu.rs | 6 + crates/horizon-client/src/recipe_book.rs | 154 +++++++++++++++--- crates/horizon-client/src/stations.rs | 3 + .../parity/VanillaRecipeBookOracle.java | 144 ++++++++++++++++ tools/test_recipe_book_parity.py | 93 +++++++++++ 10 files changed, 578 insertions(+), 85 deletions(-) create mode 100644 crates/horizon-client/examples/recipe_book_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java create mode 100644 tools/test_recipe_book_parity.py diff --git a/crates/horizon-client/examples/recipe_book_fixture.rs b/crates/horizon-client/examples/recipe_book_fixture.rs new file mode 100644 index 000000000..e165dea9b --- /dev/null +++ b/crates/horizon-client/examples/recipe_book_fixture.rs @@ -0,0 +1,143 @@ +//! The player's recipe book for tools/test_recipe_book_parity.py: reads one +//! JSON case per line (a list of give / take / seen / set / save / load ops) +//! and prints the oracle's line after each op, from +//! `horizon_client::recipe_book::{Settings, RecipeIndex}`. +//! +//! usage: recipe_book_fixture RESOURCES CASES OUTPUT +use horizon_client::recipe_book::{BookType, RecipeIndex, Settings}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{collections::BTreeSet, fs, path::Path}; + +fn fnv<'a>(ids: impl IntoIterator) -> u64 { + let mut sorted: Vec<&String> = ids.into_iter().collect(); + sorted.sort(); + let joined = sorted + .iter() + .map(|s| s.as_str()) + .collect::>() + .join(","); + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in joined.bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + h +} +fn ids(set: &BTreeSet) -> String { + format!("{}:{:x}", set.len(), fnv(set)) +} +/// The saved compound as the oracle prints it: keys sorted, lists hashed. +fn compound(tag: &Tag) -> String { + let Tag::Compound(c) = tag else { + return String::new(); + }; + let mut keys: Vec = c.keys().map(|k| k.to_string_lossy()).collect(); + keys.sort(); + let mut out = String::new(); + for k in keys { + out.push(' '); + out.push_str(&k); + out.push('='); + match tag.get(&k) { + Some(Tag::List(list)) => { + let v: Vec = list + .iter() + .map(|t| match t { + Tag::String(s) => s.to_string_lossy(), + _ => "?".into(), + }) + .collect(); + out.push_str(&format!("{}:{:x}", v.len(), fnv(&v))); + } + Some(Tag::Byte(b)) => out.push_str(&format!("{b}b")), + _ => out.push('?'), + } + } + out +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: recipe_book_fixture RESOURCES CASES OUTPUT"; + let root = Path::new(args.get(1).ok_or(usage)?); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let index = RecipeIndex::load(root); + let mut out = String::new(); + for line in cases.lines() { + let case: Value = serde_json::from_str(line)?; + let mut book = Settings::default(); + let mut saved: Option = None; + for op in case["ops"].as_array().ok_or("ops")? { + let kind = op["op"].as_str().unwrap_or_default(); + let list = || -> Vec { + op["ids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_str().map(str::to_owned)) + .filter(|id| index.contains(id)) + .collect() + }; + let mut count = 0; + let mut extra = String::new(); + match kind { + "give" => count = book.add_recipes(&index, &list()).0, + "take" => count = book.remove_recipes(&index, &list()), + "seen" => book.remove_highlight(op["id"].as_str().unwrap_or_default()), + "set" => { + let i = match op["type"].as_str().unwrap_or_default() { + "CRAFTING" => BookType::Crafting, + "FURNACE" => BookType::Furnace, + "BLAST_FURNACE" => BookType::BlastFurnace, + _ => BookType::Smoker, + } + .index(); + book.open[i] = op["open"].as_bool().unwrap_or(false); + book.filtering[i] = op["filtering"].as_bool().unwrap_or(false); + } + "save" => { + let tag = book.write(); + extra = compound(&tag); + saved = Some(tag); + } + "load" => { + let mut tag = saved + .clone() + .unwrap_or_else(|| Tag::Compound(Default::default())); + if let Tag::Compound(c) = &mut tag { + for name in ["recipes", "toBeDisplayed"] { + if let Some(Tag::List(l)) = c.get_mut(&name.into()) { + l.push(Tag::String("minecraft:no_such_recipe".into())); + l.push(Tag::String("stick".into())); + } + } + if let Some(drop) = op["drop"].as_str() { + c.remove(&drop.into()); + } + } + book = Settings::read_valid(Some(&tag), &|id| index.contains(id)); + } + other => return Err(format!("op {other}").into()), + } + let settings: String = BookType::ALL + .iter() + .map(|b| { + format!( + "{}{}", + u8::from(book.open[b.index()]), + u8::from(book.filtering[b.index()]) + ) + }) + .collect(); + out += &format!( + "{kind} {count} known={} highlight={} settings={settings}{extra}\n", + ids(&book.recipes), + ids(&book.to_be_displayed) + ); + } + out += "end\n"; + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7360723f3..1b3304e8f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3276,6 +3276,13 @@ impl Game<'_> { self.craft_recipe().map(|(_, result)| result) } /// The recipe id and result of the crafting grid. + /// `RecipeCraftingHolder.awardUsedRecipes`: a crafted recipe becomes known + /// (special ones never do). + fn award_crafted(&mut self, recipes: &[String]) { + let index = &self.res.stations.recipe_index; + let (_, unlocked) = self.level.recipe_book.add_recipes(index, recipes); + self.recipe_unlocked(&unlocked); + } 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(); @@ -3773,6 +3780,7 @@ impl Game<'_> { let carried = menu.carried.take(); let dropped = std::mem::take(&mut menu.dropped); let sounds = std::mem::take(&mut menu.sounds); + let crafted = std::mem::take(&mut menu.crafted); for (i, stack) in after.into_iter().enumerate() { if let Some(g) = game_of[i] { *self.slot_mut(g) = stack; @@ -3785,6 +3793,7 @@ impl Game<'_> { for stack in dropped { self.player_drop(stack); } + self.award_crafted(&crafted); if kind == Kind::Loom { if let Some(s) = self.station.as_mut() { s.loom.selected = usize::try_from(menu.data[0]).ok(); @@ -4053,6 +4062,7 @@ impl Game<'_> { } crafted += 1; self.stats.add("crafted", &made.0, made.1 as i32); + self.award_crafted(&[format!("minecraft:{recipe}")]); if !shift || crafted >= 64 { break; } @@ -5086,6 +5096,11 @@ impl Game<'_> { self.inventory = inventory; self.save = save; self.level = level; + // ServerRecipeBook.loadUntrusted: recipes the manager does not have are dropped. + let index = &self.res.stations.recipe_index; + let book = &mut self.level.recipe_book; + book.recipes.retain(|r| index.contains(r)); + book.to_be_displayed.retain(|r| index.contains(r)); self.dim = dim; self.world_root = save_root.clone(); self.block_ticks = Ticks::new(self.level.seed as i32); @@ -6966,7 +6981,6 @@ impl Game<'_> { self.ender_items = items.clone(); } level.ender_items = self.ender_items.clone(); - level.recipe_book.recipes = self.adv.recipes.iter().cloned().collect(); level.active_effects = self .potions .effects diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 6742e7043..d07288c9f 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -10,7 +10,7 @@ use horizon_client::{ }; use serde_json::Value; use std::{ - collections::{BTreeMap, BTreeSet, VecDeque}, + collections::{BTreeMap, VecDeque}, sync::Arc, time::Instant, }; @@ -46,7 +46,6 @@ pub(super) struct AdvState { pub(super) tree: Arc, pub(super) progress: Progress, loaded: bool, - pub(super) recipes: BTreeSet, pub(super) toasts: VecDeque, /// Awards skip the toast (`/advancement grant ... everything`). pub(super) quiet: bool, @@ -214,13 +213,9 @@ impl Game<'_> { .and_then(|t| serde_json::from_str::(&t).ok()) .map(|v| Progress::from_json(&v)) .unwrap_or_default(); - // Unlocked recipes come from the done recipe advancements' rewards. + // The known recipes are the player's own (`recipeBook`), not the + // rewards of done advancements: /recipe take sticks. let tree = self.adv.tree.clone(); - for a in &tree.list { - if progress.done(a) { - self.adv.recipes.extend(a.rewards.recipes.iter().cloned()); - } - } self.adv.progress = progress; self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect(); } @@ -375,6 +370,17 @@ impl Game<'_> { } } } + /// After `ServerRecipeBook.addRecipes`: the toast and the + /// `recipe_unlocked` trigger of each recipe now known. + pub(super) fn recipe_unlocked(&mut self, unlocked: &[String]) { + self.recipe_toast(unlocked); + for r in unlocked { + let r = r.clone(); + self.trigger("minecraft:recipe_unlocked", move |c, _| { + c["recipes"].as_str() == Some(r.as_str()) + }); + } + } /// `PlayerAdvancements.award` once done: rewards, toast, announcement. fn award(&mut self, index: usize) { let tree = self.adv.tree.clone(); @@ -383,12 +389,18 @@ impl Game<'_> { if a.rewards.experience > 0 { self.experience.give(a.rewards.experience); } - let mut unlocked = Vec::new(); - for r in &a.rewards.recipes { - if self.adv.recipes.insert(r.clone()) { - unlocked.push(r.clone()); - } - } + // ServerPlayer.awardRecipesByKey: the rewards that name a recipe. + let rewards: Vec = a + .rewards + .recipes + .iter() + .filter(|r| self.res.stations.recipe_index.contains(r)) + .cloned() + .collect(); + let (_, unlocked) = self + .level + .recipe_book + .add_recipes(&self.res.stations.recipe_index, &rewards); for table in &a.rewards.loot { let items = self .res @@ -425,12 +437,7 @@ impl Game<'_> { )); } } - self.recipe_toast(&unlocked); - for r in unlocked { - self.trigger("minecraft:recipe_unlocked", |c, _| { - c["recipes"].as_str() == Some(r.as_str()) - }); - } + self.recipe_unlocked(&unlocked); } /// `InventoryChangeTrigger`, checked when the inventory changes. pub(super) fn check_inventory_trigger(&mut self) { diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 948190d67..d440341d7 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -30,32 +30,9 @@ fn java_double_text(v: f64) -> Text { impl Game<'_> { // ---- /recipe ----------------------------------------------------------- - /// Every `minecraft:` recipe that `/recipe` can give (non-special ones). + /// Every recipe id of the recipe manager (what `/recipe` resolves and suggests). pub(super) fn learnable_recipes(&self) -> Vec { - let dir = self.options.resources.join("data/minecraft/recipe"); - let mut out = Vec::new(); - let Ok(entries) = std::fs::read_dir(&dir) else { - return out; - }; - for e in entries.flatten() { - let path = e.path(); - let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { - continue; - }; - if path.extension().and_then(|x| x.to_str()) != Some("json") { - continue; - } - let special = std::fs::read(&path) - .ok() - .and_then(|b| serde_json::from_slice::(&b).ok()) - .and_then(|v| v["type"].as_str().map(|t| t.contains("crafting_special_"))) - .unwrap_or(false); - if !special { - out.push(format!("minecraft:{stem}")); - } - } - out.sort(); - out + self.res.stations.recipe_index.ids().cloned().collect() } pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R { let targets = self.entities(ctx, "targets", true)?; @@ -73,14 +50,15 @@ impl Game<'_> { for &t in &targets { let h = holder(self.target_name(t)); let mut n = 0; - for r in &recipes { - let changed = if give { - self.adv.recipes.insert(r.clone()) - } else { - self.adv.recipes.remove(r) - }; - n += i32::from(changed); - } + // ServerPlayer.awardRecipes / resetRecipes: the displays changed. + let index = &self.res.stations.recipe_index; + n += if give { + let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes); + self.recipe_unlocked(&unlocked); + count as i32 + } else { + self.level.recipe_book.remove_recipes(index, &recipes) as i32 + }; tracker.track(&h, n); } let verb = if give { "give" } else { "take" }; diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index ee42f991f..0c6898758 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -183,11 +183,6 @@ 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 @@ -225,12 +220,7 @@ impl Game<'_> { out } fn unlocked_recipes(&self) -> BTreeSet { - self.adv - .recipes - .iter() - .chain(self.level.recipe_book.recipes.iter()) - .cloned() - .collect() + self.level.recipe_book.recipes.clone() } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { @@ -263,7 +253,6 @@ impl Game<'_> { stack.map(|s| (s.item, s.count)).hash(&mut h); } self.craft_size.hash(&mut h); - self.adv.recipes.len().hash(&mut h); self.level.recipe_book.recipes.len().hash(&mut h); self.book_filtering(book_type).hash(&mut h); self.recipe_ui.tab.map(|t| format!("{t:?}")).hash(&mut h); diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index da859aa9b..d917479a2 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -159,6 +159,8 @@ pub struct Menu { pub loom_patterns: Vec>, /// Sounds the menu plays (`ui.loom.take_result`), for the caller. pub sounds: Vec<&'static str>, + /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. + pub crafted: Vec, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -357,6 +359,7 @@ impl Menu { quick_slots: Vec::new(), loom_patterns: Vec::new(), sounds: Vec::new(), + crafted: Vec::new(), } } @@ -699,6 +702,9 @@ impl Menu { } let n = self.grid_size; let grid = self.containers[GRID].clone(); + if let Some((id, _)) = env.recipes.find(&grid, n) { + self.crafted.push(format!("minecraft:{id}")); + } let remaining = env .recipes .find(&grid, n) diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index f86c34782..b7e6685ad 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -437,42 +437,158 @@ impl Book { } } -/// The recipe book's saved state: the `recipeBook` compound of the player. +/// What the server knows of each recipe of the datapack: whether it is +/// special (`Recipe.isSpecial`: never learnable) and how many recipe book +/// displays it has (`RecipeManager.listDisplaysForRecipe`). +#[derive(Clone, Debug, Default)] +pub struct RecipeIndex { + recipes: std::collections::BTreeMap, +} +impl RecipeIndex { + /// Reads `data/minecraft/recipe/*.json` under `root`. + pub fn load(root: &std::path::Path) -> Self { + let mut recipes = std::collections::BTreeMap::new(); + let dir = root.join("data/minecraft/recipe"); + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.extension().is_none_or(|e| e != "json") { + continue; + } + let (Some(stem), Some(v)) = ( + path.file_stem().and_then(|s| s.to_str()), + std::fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()), + ) else { + continue; + }; + let kind = v["type"].as_str().unwrap_or_default(); + let special = kind.starts_with("minecraft:crafting_special_") + || kind == "minecraft:crafting_decorated_pot"; + let displays = if special { + 0 + } else if kind == "minecraft:crafting_transmute" { + // TransmuteRecipe.display: one per material count. + match &v["material_count"] { + serde_json::Value::Object(o) => { + let min = o.get("min").and_then(|m| m.as_u64()).unwrap_or(1); + let max = o.get("max").and_then(|m| m.as_u64()).unwrap_or(8); + (max.saturating_sub(min) + 1) as usize + } + _ => 1, + } + } else { + 1 + }; + recipes.insert(format!("minecraft:{stem}"), (special, displays)); + } + Self { recipes } + } + pub fn contains(&self, id: &str) -> bool { + self.recipes.contains_key(id) + } + pub fn special(&self, id: &str) -> bool { + self.recipes.get(id).is_some_and(|r| r.0) + } + pub fn displays(&self, id: &str) -> usize { + self.recipes.get(id).map_or(0, |r| r.1) + } + /// Every recipe id, in id order. + pub fn ids(&self) -> impl Iterator { + self.recipes.keys() + } +} + +/// `ServerRecipeBook`: the player's `recipeBook` compound, the known recipes +/// and the ones still to highlight (`toBeDisplayed`) with the open and +/// filter settings of each `RecipeBookType`. #[derive(Clone, Debug, Default)] pub struct Settings { /// `isGuiOpen`-style flags per `BookType`. pub open: [bool; 4], pub filtering: [bool; 4], - /// Unlocked recipe ids (`recipes`). - pub recipes: Vec, + /// Known recipe ids (`recipes`). + pub recipes: BTreeSet, /// Recipes not yet shown in the book (`toBeDisplayed`): they animate once. - pub to_be_displayed: Vec, + pub to_be_displayed: BTreeSet, } impl Settings { + /// `ServerRecipeBook.addRecipes`: the displays added (the count + /// `/recipe give` reports) and the recipes now known, in order. + pub fn add_recipes(&mut self, index: &RecipeIndex, ids: &[String]) -> (usize, Vec) { + let mut displays = 0; + let mut added = Vec::new(); + for id in ids { + if !self.recipes.contains(id) && !index.special(id) { + self.recipes.insert(id.clone()); + self.to_be_displayed.insert(id.clone()); + displays += index.displays(id); + added.push(id.clone()); + } + } + (displays, added) + } + /// `ServerRecipeBook.removeRecipes`: the displays removed. + pub fn remove_recipes(&mut self, index: &RecipeIndex, ids: &[String]) -> usize { + let mut displays = 0; + for id in ids { + if self.recipes.remove(id) { + self.to_be_displayed.remove(id); + displays += index.displays(id); + } + } + displays + } + /// `removeHighlight` (`ServerboundRecipeBookSeenRecipePacket`). + pub fn remove_highlight(&mut self, id: &str) { + self.to_be_displayed.remove(id); + } + pub fn knows(&self, id: &str) -> bool { + self.recipes.contains(id) + } + /// The compound as saved, every recipe kept. pub fn read(tag: Option<&Tag>) -> Self { + Self::read_valid(tag, &|_| true) + } + /// `ServerRecipeBook.loadUntrusted`: unknown recipes are dropped. Without + /// both lists the compound does not decode and nothing is read. + pub fn read_valid(tag: Option<&Tag>, valid: &dyn Fn(&str) -> bool) -> Self { let mut s = Self::default(); let Some(tag) = tag else { return s }; + let ids = |key: &str| match tag.get(key) { + Some(Tag::List(list)) => Some( + list.iter() + .filter_map(|t| match t { + Tag::String(id) => Some(id.to_string_lossy()), + _ => None, + }) + .map(|id| { + if id.contains(':') { + id + } else { + format!("minecraft:{id}") + } + }) + .filter(|id| valid(id)) + .collect::>(), + ), + _ => None, + }; + let (Some(recipes), Some(to_be_displayed)) = (ids("recipes"), ids("toBeDisplayed")) else { + return s; + }; let flag = |k: &str| matches!(tag.get(k), Some(Tag::Byte(b)) if *b != 0); for b in BookType::ALL { let (open, filter) = b.keys(); s.open[b.index()] = flag(open); s.filtering[b.index()] = flag(filter); } - 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(), - _ => Vec::new(), - }; - s.recipes = ids("recipes"); - s.to_be_displayed = ids("toBeDisplayed"); + s.recipes = recipes; + s.to_be_displayed = to_be_displayed; s } - /// The compound written to the player file. + /// The compound written to the player file (vanilla's lists follow an + /// identity hash order; these are sorted). pub fn write(&self) -> Tag { let mut entries: Vec<(&str, Tag)> = Vec::new(); for b in BookType::ALL { @@ -485,7 +601,7 @@ impl Settings { entries.push((filter, Tag::Byte(1))); } } - let list = |ids: &[String]| { + let list = |ids: &BTreeSet| { Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect()) }; entries.push(("recipes", list(&self.recipes))); @@ -583,7 +699,7 @@ mod tests { let mut s = Settings::default(); s.open[BookType::Furnace.index()] = true; s.filtering[BookType::Crafting.index()] = true; - s.recipes = vec!["minecraft:stick".into()]; + s.recipes = ["minecraft:stick".to_owned()].into(); let back = Settings::read(Some(&s.write())); assert_eq!(back.open, s.open); assert_eq!(back.filtering, s.filtering); diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index eee0a7442..5fdf94ab4 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -19,6 +19,8 @@ pub struct StationData { pub brewing: crate::brewing::Brewing, pub trades: crate::merchant::Trades, pub banners: crate::banner::Banners, + /// Every recipe's learnability and display count (the server recipe book). + pub recipe_index: crate::recipe_book::RecipeIndex, } impl StationData { pub fn load(root: &Path, items: &Items) -> Self { @@ -28,6 +30,7 @@ impl StationData { brewing: crate::brewing::Brewing::load(root, items), trades: crate::merchant::Trades::load(root), banners: crate::banner::Banners::load(root), + recipe_index: crate::recipe_book::RecipeIndex::load(root), } } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java new file mode 100644 index 000000000..60640010b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java @@ -0,0 +1,144 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.*; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.stats.ServerRecipeBook; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.RecipeBookType; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeManager; + +/** + * Original oracle: the player's ServerRecipeBook under a sequence of + * operations: awarding recipes (advancement rewards, /recipe give, crafting), + * taking them (/recipe take), the client seeing a highlighted recipe, the + * book settings, and saving and loading the recipeBook compound + * (ServerRecipeBook.Packed.CODEC, loadUntrusted). After each step the count + * the operation returned, the known and highlighted recipes (count and an + * FNV-1a hash of the sorted ids) and, for a save, the compound are printed. + */ +public final class VanillaRecipeBookOracle { + static long fnv(Collection ids) { + List sorted = new ArrayList<>(ids); + Collections.sort(sorted); + long h = 0xcbf29ce484222325L; + for (byte b : String.join(",", sorted).getBytes(StandardCharsets.UTF_8)) { + h ^= (b & 0xff); + h *= 0x100000001b3L; + } + return h; + } + + static String ids(Collection>> keys) { + List out = new ArrayList<>(); + for (var k : keys) out.add(k.identifier().toString()); + return out.size() + ":" + Long.toHexString(fnv(out)); + } + + static ResourceKey> key(String id) { + return ResourceKey.create(Registries.RECIPE, Identifier.parse(id)); + } + + static String compound(CompoundTag tag) { + List keys = new ArrayList<>(tag.keySet()); + Collections.sort(keys); + StringBuilder out = new StringBuilder(); + for (String k : keys) { + Tag t = tag.get(k); + out.append(' ').append(k).append('='); + if (t instanceof ListTag list) { + List v = new ArrayList<>(); + for (Tag e : list) v.add(e.asString().orElse("?")); + out.append(v.size()).append(':').append(Long.toHexString(fnv(v))); + } else { + out.append(t); + } + } + 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); + 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); + 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 { + var player = VanillaMenuOracle.make(VanillaMenuOracle.FakePlayer.class); + 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)); + player.inv = new Inventory(player, new EntityEquipment()); + ServerRecipeBook book = new ServerRecipeBook(recipes::listDisplaysForRecipe); + CompoundTag saved = null; + for (var opJson : f.getAsJsonArray("ops")) { + var op = opJson.getAsJsonObject(); + String kind = op.get("op").getAsString(); + int count = 0; + String extra = ""; + switch (kind) { + case "give", "take" -> { + List> holders = new ArrayList<>(); + for (var id : op.getAsJsonArray("ids")) { + recipes.byKey(key(id.getAsString())).ifPresent(holders::add); + } + count = kind.equals("give") ? book.addRecipes(holders, player) : book.removeRecipes(holders, player); + } + case "seen" -> book.removeHighlight(key(op.get("id").getAsString())); + case "set" -> book.setBookSetting(RecipeBookType.valueOf(op.get("type").getAsString()), + op.get("open").getAsBoolean(), op.get("filtering").getAsBoolean()); + case "save" -> { + saved = (CompoundTag) ServerRecipeBook.Packed.CODEC.encodeStart(NbtOps.INSTANCE, book.pack()).getOrThrow(); + extra = compound(saved); + } + case "load" -> { + // The saved compound with ids the manager does not know; maybe a list missing. + CompoundTag tag = saved == null ? new CompoundTag() : saved.copy(); + for (String list : List.of("recipes", "toBeDisplayed")) { + if (tag.get(list) instanceof ListTag l) { + l.add(StringTag.valueOf("minecraft:no_such_recipe")); + l.add(StringTag.valueOf("stick")); + } + } + if (op.has("drop")) tag.remove(op.get("drop").getAsString()); + book = new ServerRecipeBook(recipes::listDisplaysForRecipe); + ServerRecipeBook fresh = book; + ServerRecipeBook.Packed.CODEC.parse(NbtOps.INSTANCE, tag).result() + .ifPresent(p -> fresh.loadUntrusted(p, k -> recipes.byKey(k).isPresent())); + } + default -> throw new IllegalArgumentException(kind); + } + var packed = book.pack(); + StringBuilder settings = new StringBuilder(); + for (RecipeBookType t : RecipeBookType.values()) { + settings.append(book.isOpen(t) ? '1' : '0').append(book.isFiltering(t) ? '1' : '0'); + } + out.println(kind + " " + count + " known=" + ids(packed.known()) + " highlight=" + ids(packed.highlight()) + + " settings=" + settings + extra); + } + out.println("end"); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName() + " " + e.getMessage()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/test_recipe_book_parity.py b/tools/test_recipe_book_parity.py new file mode 100644 index 000000000..4aa91686e --- /dev/null +++ b/tools/test_recipe_book_parity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Compare the player's recipe book with vanilla's ServerRecipeBook. + +Each case runs a sequence of operations on a fresh book: awarding recipes +(advancement rewards, /recipe give, crafting; special recipes are never +learnt, and the count is the displays added), taking them back, the client +having seen a highlighted recipe, the open and filter settings of the four +book types, and saving and loading the player's recipeBook compound (with +unknown ids dropped, and a compound missing a list ignored). The Java oracle +(VanillaRecipeBookOracle) drives ServerRecipeBook and its codec; +examples/recipe_book_fixture drives horizon_client::recipe_book. After each +operation the count, the known and highlighted recipes, the settings and +the saved compound are compared. +""" +import argparse +import json +import random +try: + from . import interaction_lab as lib +except ImportError: + import interaction_lab as lib + +TYPES = ['CRAFTING', 'FURNACE', 'BLAST_FURNACE', 'SMOKER'] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=5) + parser.add_argument('--cases', type=int, default=1500) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + work = lib.work_dir('recipe-book-parity') + vanilla = lib.Vanilla(work) + vanilla.compile('ParityData', 'VanillaMenuOracle', 'VanillaRecipeBookOracle') + ids = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')) + rng = random.Random(args.seed) + cases = [] + for _ in range(args.cases): + ops, known = [], set() + for _ in range(rng.randrange(1, 12)): + kind = rng.choices(['give', 'take', 'seen', 'set', 'save', 'load'], [10, 4, 4, 3, 3, 2])[0] + if kind in ('give', 'take'): + pool = list(known) if kind == 'take' and known and rng.random() < 0.7 else ids + chosen = ids if rng.random() < 0.03 else rng.sample(pool, min(len(pool), rng.choice([1, 1, 2, 5, 20]))) + if rng.random() < 0.2: + chosen = chosen + chosen[:1] + ops.append({'op': kind, 'ids': chosen}) + if kind == 'give': + known.update(chosen) + elif kind == 'seen': + ops.append({'op': kind, 'id': rng.choice(list(known) or ids)}) + elif kind == 'set': + ops.append({'op': kind, 'type': rng.choice(TYPES), 'open': rng.random() < 0.5, 'filtering': rng.random() < 0.5}) + elif kind == 'save': + ops.append({'op': kind}) + else: + op = {'op': kind} + if rng.random() < 0.2: + op['drop'] = rng.choice(['recipes', 'toBeDisplayed']) + ops.append(op) + cases.append({'ops': ops}) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + vanilla.run('VanillaRecipeBookOracle', work / 'cases.jsonl', work / 'native.txt') + lib.cargo_example('horizon-client', 'recipe_book_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + + def by_case(path): + out, cur = [], [] + for line in path.read_text().splitlines(): + cur.append(line) + if line == 'end' or line.startswith('error-case'): + out.append(cur) + cur = [] + return out + native, rust = by_case(work / 'native.txt'), by_case(work / 'rust.txt') + 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), min(len(a), len(b))) + op = case['ops'][step]['op'] if step < len(case['ops']) else 'end' + bad.setdefault(op, []).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 {json.dumps(case["ops"][:step + 1])[:600]}') + print(f' native {a[step] if step < len(a) else "-"}\n rust {b[step] if step < len(b) else "-"}') + errors = sum(1 for c in native if c and c[-1].startswith('error-case')) + print(f'{len(cases) - total}/{len(cases)} cases match ({errors} oracle errors)') + raise SystemExit(1 if total or errors or len(native) != len(cases) else 0) + + +if __name__ == '__main__': + main() From 8ba728287f510d0ec624de14f7aff7e8843a7cd7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:14:14 +0200 Subject: [PATCH 5/7] Order the recipe book's buttons as the vanilla client does ClientRecipeBook keeps the displays it was sent in a HashMap of display ids, whose iteration order (buckets, then arrival) orders the collections; the game now keeps such a client book (on the verified Java HashMap port) synced with the server book, with display ids numbered as RecipeManager does. A new harness runs the client's ClientRecipeBook, RecipeCollection selection and the tab and page logic of RecipeBookComponent over 1,200 cases. Co-Authored-By: Claude Opus 5.5 --- .../examples/recipe_book_view_fixture.rs | 121 ++++++++++ crates/horizon-client/src/game/recipe_book.rs | 63 ++++- crates/horizon-client/src/menu/place.rs | 5 +- crates/horizon-client/src/recipe_book.rs | 225 +++++++++++++----- .../parity/VanillaRecipeBookViewOracle.java | 140 +++++++++++ tools/test_recipe_book_view_parity.py | 93 ++++++++ 6 files changed, 576 insertions(+), 71 deletions(-) create mode 100644 crates/horizon-client/examples/recipe_book_view_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java create mode 100644 tools/test_recipe_book_view_parity.py diff --git a/crates/horizon-client/examples/recipe_book_view_fixture.rs b/crates/horizon-client/examples/recipe_book_view_fixture.rs new file mode 100644 index 000000000..5c4f5bb26 --- /dev/null +++ b/crates/horizon-client/examples/recipe_book_view_fixture.rs @@ -0,0 +1,121 @@ +//! What the recipe book lists, for tools/test_recipe_book_view_parity.py: +//! reads one JSON case per line (the history of displays the client was +//! sent, the book type and grid, the inventory and menu slots, the filter) +//! and prints every tab's visibility, page count and buttons from +//! `horizon_client::recipe_book::ClientBook`. +//! +//! usage: recipe_book_view_fixture RESOURCES CASES OUTPUT +use horizon_client::{ + crafting::Recipes, + item_data::parse_stack, + items::Items, + menu::place::Stacked, + recipe_book::{Book, BookType, ClientBook, Display, RecipeIndex, Tab}, +}; +use serde_json::Value; +use std::{fmt::Write as _, fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: recipe_book_view_fixture RESOURCES CASES OUTPUT"; + let root = Path::new(args.get(1).ok_or(usage)?); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let index = RecipeIndex::load(root); + let mut book = Book::build(&recipes, &items); + book.set_display_ids(&index); + let max = |s: &horizon_client::items::ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack); + let mut out = String::new(); + for line in cases.lines() { + let case: Value = serde_json::from_str(line)?; + let mut client = ClientBook::default(); + for batch in case["history"].as_array().ok_or("history")? { + let op = batch["op"].as_str().unwrap_or_default(); + if op == "replace" { + client.clear(); + } + for id in batch["ids"].as_array().into_iter().flatten() { + for d in index.display_ids(id.as_str().unwrap_or_default()) { + if op == "remove" { + client.remove(d); + } else { + client.add(d); + } + } + } + } + let kind = case["type"].as_str().unwrap_or_default(); + let grid = case["grid"].as_u64().unwrap_or(3) as usize; + let mut stock = Stacked::default(); + for s in case["inventory"].as_array().into_iter().flatten() { + if let Some(stack) = parse_stack(s.as_str().unwrap_or("-"))? { + stock.account_simple(&stack, max(&stack)); + } + } + for s in case["slots"].as_array().into_iter().flatten() { + if let Some(stack) = parse_stack(s.as_str().unwrap_or("-"))? { + if kind == "crafting" { + stock.account_simple(&stack, max(&stack)); + } else { + stock.account_stack(&stack, max(&stack)); + } + } + } + let book_type = match kind { + "crafting" => BookType::Crafting, + "furnace" => BookType::Furnace, + "blast_furnace" => BookType::BlastFurnace, + _ => BookType::Smoker, + }; + let filtering = case["filtering"].as_bool().unwrap_or(false); + for tab in book_type.tabs() { + let collections = client.collections(&book, book_type, tab); + let selected = |i: usize| match (&book.entries[i].display, book_type) { + (Display::Furnace(_), BookType::Crafting) => false, + (Display::Furnace(_), _) => true, + (_, BookType::Crafting) => book.entries[i].fits(grid, grid), + _ => false, + }; + let craftable = |i: usize| selected(i) && book.can_craft(&book.entries[i], &stock); + let visible = tab == Tab::Search + || collections + .iter() + .any(|c| c.entries.iter().any(|&i| selected(i))); + let shown: Vec<_> = collections + .iter() + .filter(|c| c.entries.iter().any(|&i| selected(i))) + .filter(|c| !filtering || c.entries.iter().any(|&i| craftable(i))) + .collect(); + let name = match tab { + Tab::Search => "search".to_owned(), + Tab::Category(c) => c.name().to_owned(), + }; + let _ = write!( + out, + "{name} {} pages={}", + if visible { "shown" } else { "hidden" }, + shown.len().div_ceil(20) + ); + for c in shown { + let parts: Vec = c + .entries + .iter() + .map(|&i| { + format!( + "{}{}{}", + book.entries[i].display_id, + if selected(i) { "s" } else { "" }, + if craftable(i) { "c" } else { "" } + ) + }) + .collect(); + let _ = write!(out, " [{}]", parts.join(",")); + } + out.push_str(" | "); + } + out.push('\n'); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 0c6898758..ca9fe9d89 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -10,7 +10,7 @@ use horizon_client::{ hud::{HudBatch, Rect, rgba}, items::ItemStack, menu::place::{PostPlace, Stacked}, - recipe_book::{Book, BookType, Collection, Display, Entry, Tab}, + recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab}, ui::EditBox, }; use std::{ @@ -72,6 +72,11 @@ pub(super) struct RecipeUi { /// Squeeze animations of new recipes: ticks left per button index and tab. button_anim: Vec<(usize, f32)>, tab_anim: Vec<(Tab, f32)>, + /// The client's copy of the known recipes (`ClientRecipeBook`), its + /// order deciding the buttons', and the recipes it was last synced with. + client: ClientBook, + client_known: Option>, + client_version: u64, } impl RecipeUi { @@ -219,12 +224,44 @@ impl Game<'_> { }); out } - fn unlocked_recipes(&self) -> BTreeSet { - self.level.recipe_book.recipes.clone() + /// Sends the client book what changed in the server's: the first time a + /// replacing batch (vanilla's server iterates an identity hash set; this + /// one goes in id order), then each unlock and removal. + fn sync_client_book(&mut self) { + let known = &self.level.recipe_book.recipes; + let index = &self.res.stations.recipe_index; + let ui = &mut self.recipe_ui; + match ui.client_known.as_ref() { + Some(previous) if previous == known => return, + Some(previous) => { + for id in previous.difference(known) { + for d in index.display_ids(id) { + ui.client.remove(d); + } + } + for id in known.difference(previous) { + for d in index.display_ids(id) { + ui.client.add(d); + } + } + } + None => { + ui.client.clear(); + for id in known { + for d in index.display_ids(id) { + ui.client.add(d); + } + } + } + } + ui.client_known = Some(known.clone()); + ui.client_version += 1; } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { - self.recipe_ui.book = Some(Book::build(&self.res.recipes, &self.res.items)); + let mut book = Book::build(&self.res.recipes, &self.res.items); + book.set_display_ids(&self.res.stations.recipe_index); + self.recipe_ui.book = Some(book); } if self.recipe_ui.search.is_none() { let mut search = EditBox::new(0.0, 0.0, 81.0, 14.0); @@ -237,6 +274,7 @@ impl Game<'_> { /// Rebuilds the tab and button lists when anything they depend on changed. fn refresh_book_view(&mut self, book_type: BookType) { self.ensure_book(); + self.sync_client_book(); let mut h = std::collections::hash_map::DefaultHasher::new(); for s in self.inventory.iter().flatten() { (&s.item, s.count, s.damage).hash(&mut h); @@ -253,7 +291,7 @@ impl Game<'_> { stack.map(|s| (s.item, s.count)).hash(&mut h); } self.craft_size.hash(&mut h); - self.level.recipe_book.recipes.len().hash(&mut h); + self.recipe_ui.client_version.hash(&mut h); self.book_filtering(book_type).hash(&mut h); self.recipe_ui.tab.map(|t| format!("{t:?}")).hash(&mut h); self.recipe_ui @@ -287,7 +325,6 @@ impl Game<'_> { 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); @@ -301,8 +338,10 @@ impl Game<'_> { if tab == Tab::Search { continue; } - let hit = book - .collections(&unlocked, book_type, tab) + let hit = self + .recipe_ui + .client + .collections(&book, book_type, tab) .iter() .flat_map(|c| c.entries.iter()) .any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i])); @@ -345,7 +384,6 @@ impl Game<'_> { let Some(book) = ui.book.as_ref() else { return View::default(); }; - let unlocked = self.unlocked_recipes(); let available = self.book_available(book_type); let (gw, gh) = self.book_grid(); let selected = |e: &Entry| match book_type { @@ -357,8 +395,9 @@ impl Game<'_> { let mut tabs = Vec::new(); for tab in book_type.tabs() { let visible = tab == Tab::Search - || book - .collections(&unlocked, book_type, tab) + || ui + .client + .collections(book, book_type, tab) .iter() .any(|c| c.entries.iter().any(|&i| selected(&book.entries[i]))); if visible { @@ -371,7 +410,7 @@ impl Game<'_> { .as_ref() .map(|s| s.value.clone()) .unwrap_or_default(); - let collections: Vec = book.collections(&unlocked, book_type, tab); + let collections: Vec = ui.client.collections(book, book_type, tab); let mut buttons = Vec::new(); for c in collections { if !c.entries.iter().any(|&i| selected(&book.entries[i])) { diff --git a/crates/horizon-client/src/menu/place.rs b/crates/horizon-client/src/menu/place.rs index 97363c301..9bd08afe2 100644 --- a/crates/horizon-client/src/menu/place.rs +++ b/crates/horizon-client/src/menu/place.rs @@ -79,9 +79,10 @@ impl Stacked { &self.keys } /// `canCraft(ingredients, null)` without touching the counts (the recipe - /// book's craftable test; the answer does not depend on the order). + /// book's craftable test; the answer does not depend on the order; no + /// ingredients at all can always be found). pub fn can_craft(&self, ingredients: &[&Ingredient]) -> bool { - !ingredients.is_empty() && self.clone().try_pick(ingredients, 1, None) + self.clone().try_pick(ingredients, 1, None) } /// `getResultUpperBound`. fn upper_bound(&self, ingredients: &[&Ingredient]) -> i32 { diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index b7e6685ad..331a215a4 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -89,6 +89,23 @@ pub enum Category { BlastMisc, SmokerFood, } +impl Category { + /// The `RecipeBookCategories` registry path. + pub fn name(self) -> &'static str { + match self { + Self::CraftingBuilding => "crafting_building_blocks", + Self::CraftingRedstone => "crafting_redstone", + Self::CraftingEquipment => "crafting_equipment", + Self::CraftingMisc => "crafting_misc", + Self::FurnaceFood => "furnace_food", + Self::FurnaceBlocks => "furnace_blocks", + Self::FurnaceMisc => "furnace_misc", + Self::BlastBlocks => "blast_furnace_blocks", + Self::BlastMisc => "blast_furnace_misc", + Self::SmokerFood => "smoker_food", + } + } +} /// A tab button: the search tab or one category. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Tab { @@ -133,6 +150,9 @@ pub enum Display { pub struct Entry { /// The recipe id, `minecraft:name`. pub id: String, + /// `RecipeDisplayId`: the display's index among every recipe's displays + /// (`Book::set_display_ids`; -1 until then). + pub display_id: i32, pub category: Category, pub group: Option, pub display: Display, @@ -289,6 +309,7 @@ impl Book { for (display, result) in special.book_displays() { entries.push(Entry { id: format!("minecraft:{name}"), + display_id: -1, category: crafting_category(&category), group: group(&grp), display, @@ -300,6 +321,7 @@ impl Book { }; entries.push(Entry { id: format!("minecraft:{name}"), + display_id: -1, category: crafting_category(&category), group: group(&grp), display, @@ -318,6 +340,7 @@ impl Book { }; entries.push(Entry { id: format!("minecraft:{}", c.id), + display_id: -1, category, group: group(&c.group), display: Display::Furnace(c.ingredient.clone()), @@ -340,42 +363,6 @@ impl Book { order, } } - /// The unlocked recipes of one tab as collections (`ClientRecipeBook.rebuildCollections`). - pub fn collections( - &self, - unlocked: &BTreeSet, - book: BookType, - tab: Tab, - ) -> Vec { - let categories: Vec = match tab { - Tab::Search => book.search_categories().to_vec(), - Tab::Category(c) => vec![c], - }; - let mut out = Vec::new(); - for category in categories { - let mut by_group: HashMap<&str, usize> = HashMap::new(); - let start = out.len(); - for (i, e) in self.entries.iter().enumerate() { - if e.category != category || !unlocked.contains(&e.id) { - continue; - } - match e.group.as_deref().and_then(|g| by_group.get(g).copied()) { - Some(c) => { - let c: usize = c; - let collection: &mut Collection = &mut out[start + c]; - collection.entries.push(i); - } - None => { - if let Some(g) = e.group.as_deref() { - by_group.insert(g, out.len() - start); - } - out.push(Collection { entries: vec![i] }); - } - } - } - } - out - } /// Which book a recipe id belongs to. pub fn book_of(&self, id: &str) -> Option { let e = self.entries.iter().find(|e| e.id == id)?; @@ -391,12 +378,29 @@ impl Book { Category::SmokerFood => BookType::Smoker, }) } - /// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients can - /// all be found in `stock`. + /// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients + /// (`craftingRequirements`) 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::>()) - }) + self.placements + .get(&entry.id) + .is_some_and(|p| stock.can_craft(&p.ingredients.iter().collect::>())) + } + /// Numbers the entries as `RecipeManager.unpackRecipeInfo` numbers the + /// displays: every recipe in id order, each with its displays. + pub fn set_display_ids(&mut self, index: &RecipeIndex) { + let mut previous: Option<(String, i32)> = None; + for e in &mut self.entries { + let next = match &previous { + Some((id, last)) if *id == e.id => last + 1, + _ => index.first_display(&e.id).unwrap_or(-1), + }; + e.display_id = next; + previous = Some((e.id.clone(), next)); + } + } + /// The entry of a display id. + pub fn entry_of_display(&self, display: i32) -> Option { + self.entries.iter().position(|e| e.display_id == display) } pub fn entry(&self, id: &str) -> Option<&Entry> { self.entries.iter().find(|e| e.id == id) @@ -437,12 +441,94 @@ impl Book { } } +/// A `RecipeDisplayId` as a `HashMap` key: a record of one int hashes as it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DisplayKey(i32); +impl horizon_world::java_hash_map::JavaKey for DisplayKey { + fn java_hash(&self) -> i32 { + self.0 + } + fn tie_break(&self, other: &Self) -> std::cmp::Ordering { + if self.0 < other.0 { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Greater + } + } +} + +/// `ClientRecipeBook`: the displays the client was sent, in a `HashMap` whose +/// iteration order (the display ids' buckets, then arrival order) decides the +/// order of the book's buttons. +#[derive(Default)] +pub struct ClientBook { + known: horizon_world::java_hash_map::JavaHashMap, + pub highlight: std::collections::HashSet, +} +impl ClientBook { + pub fn add(&mut self, display: i32) { + self.known.put(DisplayKey(display), ()); + } + pub fn remove(&mut self, display: i32) { + self.known.remove(&DisplayKey(display)); + self.highlight.remove(&display); + } + /// `clear` (a replacing `ClientboundRecipeBookAddPacket`): the table keeps its size. + pub fn clear(&mut self) { + self.known.clear(); + self.highlight.clear(); + } + /// The known display ids in iteration order. + pub fn displays(&self) -> Vec { + self.known.entries().map(|(k, _)| k.0).collect() + } + /// `rebuildCollections` then `getCollection(tab)`: per category, a + /// collection per entry without a group or per group, in the order the + /// known displays iterate; the search tab lists its categories in turn. + pub fn collections(&self, book: &Book, book_type: BookType, tab: Tab) -> Vec { + let by_display: HashMap = book + .entries + .iter() + .enumerate() + .map(|(i, e)| (e.display_id, i)) + .collect(); + let mut by_category: HashMap> = HashMap::new(); + let mut groups: HashMap<(Category, String), (Category, usize)> = HashMap::new(); + for display in self.displays() { + let Some(&i) = by_display.get(&display) else { + continue; + }; + let e = &book.entries[i]; + let list = by_category.entry(e.category).or_default(); + match &e.group { + None => list.push(Collection { entries: vec![i] }), + Some(g) => match groups.get(&(e.category, g.clone())) { + Some(&(_, at)) => list[at].entries.push(i), + None => { + groups.insert((e.category, g.clone()), (e.category, list.len())); + list.push(Collection { entries: vec![i] }); + } + }, + } + } + let categories: Vec = match tab { + Tab::Search => book_type.search_categories().to_vec(), + Tab::Category(c) => vec![c], + }; + categories + .into_iter() + .flat_map(|c| by_category.remove(&c).unwrap_or_default()) + .collect() + } +} + /// What the server knows of each recipe of the datapack: whether it is /// special (`Recipe.isSpecial`: never learnable) and how many recipe book /// displays it has (`RecipeManager.listDisplaysForRecipe`). #[derive(Clone, Debug, Default)] pub struct RecipeIndex { - recipes: std::collections::BTreeMap, + /// Recipe id -> (special, display count, first display id). + recipes: std::collections::BTreeMap, } impl RecipeIndex { /// Reads `data/minecraft/recipe/*.json` under `root`. @@ -480,7 +566,13 @@ impl RecipeIndex { } else { 1 }; - recipes.insert(format!("minecraft:{stem}"), (special, displays)); + recipes.insert(format!("minecraft:{stem}"), (special, displays, 0)); + } + // RecipeManager keeps its recipes sorted by id and numbers the displays in that order. + let mut next = 0; + for r in recipes.values_mut() { + r.2 = next; + next += r.1 as i32; } Self { recipes } } @@ -497,6 +589,13 @@ impl RecipeIndex { pub fn ids(&self) -> impl Iterator { self.recipes.keys() } + /// The display ids of a recipe (none for a special one). + pub fn display_ids(&self, id: &str) -> std::ops::Range { + self.recipes.get(id).map_or(0..0, |r| r.2..r.2 + r.1 as i32) + } + pub fn first_display(&self, id: &str) -> Option { + self.recipes.get(id).filter(|r| r.1 > 0).map(|r| r.2) + } } /// `ServerRecipeBook`: the player's `recipeBook` compound, the known recipes @@ -642,8 +741,9 @@ mod tests { } #[test] fn collections_group_recipes_of_a_category() { - let entry = |id: &str, group: Option<&str>, category| Entry { + let entry = |id: &str, display_id, group: Option<&str>, category| Entry { id: id.into(), + display_id, category, group: group.map(str::to_owned), display: Display::Shapeless(vec![ing(&["minecraft:stick"])]), @@ -651,34 +751,45 @@ mod tests { }; let book = Book { entries: vec![ - entry("minecraft:a", Some("planks"), Category::CraftingBuilding), - entry("minecraft:b", Some("planks"), Category::CraftingBuilding), - entry("minecraft:c", None, Category::CraftingBuilding), - entry("minecraft:d", Some("planks"), Category::CraftingMisc), + entry("minecraft:a", 0, Some("planks"), Category::CraftingBuilding), + entry("minecraft:b", 1, Some("planks"), Category::CraftingBuilding), + entry("minecraft:c", 2, None, Category::CraftingBuilding), + entry("minecraft:d", 3, Some("planks"), Category::CraftingMisc), ], placements: HashMap::new(), order: HashMap::new(), }; - let unlocked: BTreeSet = ["a", "b", "c", "d"] - .iter() - .map(|n| format!("minecraft:{n}")) - .collect(); + let mut client = ClientBook::default(); + for d in 0..4 { + client.add(d); + } let tab = Tab::Category(Category::CraftingBuilding); - let c = book.collections(&unlocked, BookType::Crafting, tab); + let c = client.collections(&book, BookType::Crafting, tab); assert_eq!(c.len(), 2); assert_eq!(c[0].entries, vec![0, 1]); // The search tab lists every category; the same group in another category is separate. - let all = book.collections(&unlocked, BookType::Crafting, Tab::Search); + let all = client.collections(&book, BookType::Crafting, Tab::Search); assert_eq!(all.len(), 3); - // Locked recipes are hidden. - let some: BTreeSet = ["minecraft:c".to_owned()].into(); - assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1); + // Displays the client was not sent are not listed. + client.clear(); + client.add(2); + assert_eq!(client.collections(&book, BookType::Crafting, tab).len(), 1); + } + #[test] + fn display_ids_collide_in_a_small_table() { + // A 16-bucket table: 17 and 1 share a bucket and keep arrival order. + let mut client = ClientBook::default(); + for d in [17, 3, 1] { + client.add(d); + } + assert_eq!(client.displays(), vec![17, 1, 3]); } #[test] fn search_reads_tooltip_lines_and_ids() { let book = Book { entries: vec![Entry { id: "minecraft:stick".into(), + display_id: 0, category: Category::CraftingMisc, group: None, display: Display::Shapeless(Vec::new()), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java new file mode 100644 index 000000000..98e1add63 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java @@ -0,0 +1,140 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.client.ClientRecipeBook; +import net.minecraft.client.gui.screens.recipebook.RecipeCollection; +import net.minecraft.client.gui.screens.recipebook.SearchRecipeBookCategory; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.player.StackedItemContents; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.ExtendedRecipeBookCategory; +import net.minecraft.world.item.crafting.RecipeBookCategories; +import net.minecraft.world.item.crafting.RecipeManager; +import net.minecraft.world.item.crafting.display.FurnaceRecipeDisplay; +import net.minecraft.world.item.crafting.display.RecipeDisplay; +import net.minecraft.world.item.crafting.display.RecipeDisplayEntry; +import net.minecraft.world.item.crafting.display.ShapedCraftingRecipeDisplay; +import net.minecraft.world.item.crafting.display.ShapelessCraftingRecipeDisplay; + +/** + * Original oracle for what the recipe book screen lists: the client's + * ClientRecipeBook receives the displays of the known recipes (in the order + * the server sent them, then later unlocks and removals) and rebuilds its + * collections; each collection selects its recipes for the open menu + * (CraftingRecipeBookComponent / FurnaceRecipeBookComponent.selectMatchingRecipes) + * with the stacked contents of the inventory and the menu slots; then for + * every tab of the book RecipeBookTabButton.updateVisibility and + * RecipeBookComponent.updateCollections (without a search) decide the + * buttons. Printed per tab: visibility, the page count, and each button's + * displays with their selected and craftable flags. + */ +public final class VanillaRecipeBookViewOracle { + record Tab(ExtendedRecipeBookCategory category, String name) {} + + static List tabs(String type) { + return switch (type) { + case "crafting" -> List.of(new Tab(SearchRecipeBookCategory.CRAFTING, "search"), + new Tab(RecipeBookCategories.CRAFTING_EQUIPMENT, "crafting_equipment"), + new Tab(RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, "crafting_building_blocks"), + new Tab(RecipeBookCategories.CRAFTING_MISC, "crafting_misc"), + new Tab(RecipeBookCategories.CRAFTING_REDSTONE, "crafting_redstone")); + case "furnace" -> List.of(new Tab(SearchRecipeBookCategory.FURNACE, "search"), + new Tab(RecipeBookCategories.FURNACE_FOOD, "furnace_food"), + new Tab(RecipeBookCategories.FURNACE_BLOCKS, "furnace_blocks"), + new Tab(RecipeBookCategories.FURNACE_MISC, "furnace_misc")); + case "blast_furnace" -> List.of(new Tab(SearchRecipeBookCategory.BLAST_FURNACE, "search"), + new Tab(RecipeBookCategories.BLAST_FURNACE_BLOCKS, "blast_furnace_blocks"), + new Tab(RecipeBookCategories.BLAST_FURNACE_MISC, "blast_furnace_misc")); + default -> List.of(new Tab(SearchRecipeBookCategory.SMOKER, "search"), + new Tab(RecipeBookCategories.SMOKER_FOOD, "smoker_food")); + }; + } + + static List displays(RecipeManager recipes, String id) { + List out = new ArrayList<>(); + recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(id)), out::add); + return out; + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + RecipeManager 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 { + ClientRecipeBook book = new ClientRecipeBook(); + // ClientPacketListener.handleRecipeBookAdd / handleRecipeBookRemove. + for (var batch : f.getAsJsonArray("history")) { + var b = batch.getAsJsonObject(); + String op = b.get("op").getAsString(); + if (op.equals("replace")) book.clear(); + for (var id : b.getAsJsonArray("ids")) { + for (RecipeDisplayEntry entry : displays(recipes, id.getAsString())) { + if (op.equals("remove")) book.remove(entry.id()); + else book.add(entry); + } + } + book.rebuildCollections(); + } + StackedItemContents contents = new StackedItemContents(); + for (var s : f.getAsJsonArray("inventory")) contents.accountSimpleStack(ParityData.stack(s.getAsString())); + String type = f.get("type").getAsString(); + int grid = f.get("grid").getAsInt(); + for (var s : f.getAsJsonArray("slots")) { + ItemStack stack = ParityData.stack(s.getAsString()); + // A furnace's SimpleContainer counts every slot; the crafting grid only simple stacks. + if (type.equals("crafting")) contents.accountSimpleStack(stack); + else contents.accountStack(stack); + } + Predicate canDisplay = type.equals("crafting") + ? display -> switch (display) { + case ShapedCraftingRecipeDisplay shaped -> grid >= shaped.width() && grid >= shaped.height(); + case ShapelessCraftingRecipeDisplay shapeless -> grid * grid >= shapeless.ingredients().size(); + default -> false; + } + : display -> display instanceof FurnaceRecipeDisplay; + List tabs = tabs(type); + for (Tab tab : tabs) { + for (RecipeCollection c : book.getCollection(tab.category())) c.selectRecipes(contents, canDisplay); + } + boolean filtering = f.get("filtering").getAsBoolean(); + StringBuilder result = new StringBuilder(); + for (Tab tab : tabs) { + List collections = new ArrayList<>(book.getCollection(tab.category())); + boolean visible = tab.category() instanceof SearchRecipeBookCategory || collections.stream().anyMatch(RecipeCollection::hasAnySelected); + result.append(tab.name()).append(visible ? " shown" : " hidden"); + collections.removeIf(c -> !c.hasAnySelected()); + if (filtering) collections.removeIf(c -> !c.hasCraftable()); + result.append(" pages=").append((int) Math.ceil(collections.size() / 20.0)); + for (RecipeCollection c : collections) { + result.append(" ["); + boolean first = true; + for (RecipeDisplayEntry e : c.getRecipes()) { + boolean selected = c.getSelectedRecipes(RecipeCollection.CraftableStatus.ANY).contains(e); + result.append(first ? "" : ",").append(e.id().index()).append(selected ? "s" : "").append(c.isCraftable(e.id()) ? "c" : ""); + first = false; + } + result.append(']'); + } + result.append(" | "); + } + out.println(result); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName() + " " + e.getMessage()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/test_recipe_book_view_parity.py b/tools/test_recipe_book_view_parity.py new file mode 100644 index 000000000..eeca5c4fb --- /dev/null +++ b/tools/test_recipe_book_view_parity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Compare what the recipe book lists with the vanilla client's. + +Each case sends the client recipe book a history of displays as the server +does (the initial replacing batch in some order, later unlocks and +removals), opens a book type (the inventory's 2x2 or a crafting table's 3x3 +grid, the furnace, blast furnace or smoker) with random inventory and menu +contents and the craftable filter on or off. The Java oracle +(VanillaRecipeBookViewOracle, on the client jar) runs ClientRecipeBook, +RecipeCollection.selectRecipes and the tab and page logic of +RecipeBookComponent; examples/recipe_book_view_fixture runs +horizon_client::recipe_book::ClientBook. Per tab: visibility, pages and +every button's displays with their selected and craftable flags, in order +(the client's HashMap of display ids decides it). +""" +import argparse +import json +import os +import random +import subprocess +import sys +try: + from . import interaction_lab as lib, lab, test_place_recipe_parity as place, test_model_baking_parity as baking + from . import test_crafter_parity as crafter, test_rust_parity as base +except ImportError: + import interaction_lab as lib + import lab + import test_place_recipe_parity as place + import test_model_baking_parity as baking + import test_crafter_parity as crafter + import test_rust_parity as base + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=17) + parser.add_argument('--cases', type=int, default=1200) + parser.add_argument('--limit', type=int, default=2) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + work = lib.work_dir('recipe-book-view-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps, + '-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'VanillaRecipeBookViewOracle'))], + capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + items = json.loads((lib.RESOURCES / 'items.json').read_text()) + recipes = crafter.Recipes(lib.RESOURCES) + gen = place.Gen(random.Random(args.seed), items, recipes) + rng = gen.rng + ids = sorted('minecraft:' + n for n in recipes.recipes) + cases = [] + for n in range(args.cases): + kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5] + # Few to most recipes known: the table grows and display ids collide. + known = rng.sample(ids, rng.choice([5, 30, 100, 300, 600, 900, len(ids)])) + history = [{'op': 'replace', 'ids': known}] + for _ in range(rng.choice([0, 0, 1, 2, 3])): + if rng.random() < 0.6: + history.append({'op': 'add', 'ids': rng.sample(ids, rng.choice([1, 3, 20]))}) + else: + history.append({'op': 'remove', 'ids': rng.sample(known, min(len(known), rng.choice([1, 5, 40])))}) + if rng.random() < 0.1: + history.append({'op': 'replace', 'ids': rng.sample(ids, 50)}) + menu = {'crafting': rng.choice(['inventory', 'crafting']), 'furnace': 'furnace', 'blast_furnace': 'blast_furnace', + 'smoker': 'smoker'}[kind] + case = gen.case(menu) + inventory = [s for _, s in case['inventory']] + slots = [s for _, s in case['grid']] + cases.append({'type': kind, 'grid': 2 if menu == 'inventory' else 3, 'history': history, 'inventory': inventory, + 'slots': slots, 'filtering': rng.random() < 0.5}) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaRecipeBookViewOracle', + str(work / 'cases.jsonl'), str(work / 'native.txt')], capture_output=True, text=True) + if run.returncode: + print(run.stderr[-4000:]) + sys.exit('oracle failed') + lib.cargo_example('horizon-client', 'recipe_book_view_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + + def describe(case): + return json.dumps({k: (v if k != 'history' else [(h['op'], len(h['ids'])) for h in v]) for k, v in case.items() + if k not in ('inventory', 'slots')}) + bad = lib.compare(cases, work / 'native.txt', work / 'rust.txt', lambda case, line: case['type'] if not line.startswith('error') + else 'oracle error', describe=describe, limit=args.limit) + raise SystemExit(1 if bad else 0) + + +if __name__ == '__main__': + main() From b5c0bf7859fcab6f5ecb6ae704eecd9bbd6603e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:38:25 +0200 Subject: [PATCH 6/7] Draw the loom and crafter screens as the vanilla client does LoomScreen.extractBackground (slot icons, scroller, pattern buttons with their swatches and tooltip, the result banner or the six-layer error) and CrafterScreen's background, disabled slots and redstone arrow become screen_layout calls the game paints. A new harness runs vanilla's screens on stand-in menus and compares 1,600 call lists. Co-Authored-By: Claude Opus 5.5 --- .../examples/screen_layout_fixture.rs | 138 +++++++++ crates/horizon-client/src/game/loom.rs | 239 ++++++++------- .../src/game/machines/crafter.rs | 55 ++-- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/screen_layout.rs | 265 ++++++++++++++++ .../parity/VanillaLoomScreenOracle.java | 282 ++++++++++++++++++ tools/test_screen_layout_parity.py | 119 ++++++++ 7 files changed, 963 insertions(+), 136 deletions(-) create mode 100644 crates/horizon-client/examples/screen_layout_fixture.rs create mode 100644 crates/horizon-client/src/screen_layout.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java create mode 100644 tools/test_screen_layout_parity.py diff --git a/crates/horizon-client/examples/screen_layout_fixture.rs b/crates/horizon-client/examples/screen_layout_fixture.rs new file mode 100644 index 000000000..f364037ab --- /dev/null +++ b/crates/horizon-client/examples/screen_layout_fixture.rs @@ -0,0 +1,138 @@ +//! Loom and crafter screen drawing for tools/test_screen_layout_parity.py: +//! reads one JSON case per line and prints the `horizon_client::screen_layout` +//! calls in the format of `VanillaLoomScreenOracle`. +//! +//! usage: screen_layout_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + banner::{BannerLayer, Banners, banner_color}, + screen_layout::{self, CrafterView, LoomView, ScreenDraw}, +}; +use serde_json::{Value, json}; +use std::{fs, path::Path, sync::Arc}; + +fn draw_json(d: &ScreenDraw) -> Value { + let round = |v: f32| ((v * 1e6).round() / 1e6) as f64; + match d { + ScreenDraw::Gradient { x1, y1 } => json!({"t": "gradient", "x1": x1, "y1": y1}), + ScreenDraw::Blit { + texture, + x, + y, + w, + h, + tw, + th, + } => { + json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h, "u": 0.0, "v": 0.0, "tw": tw, "th": th}) + } + ScreenDraw::Sprite { id, x, y, w, h } => { + json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h}) + } + ScreenDraw::Banner { + base, + layers, + x0, + y0, + x1, + y1, + } => { + let layers: Vec = layers + .iter() + .map(|l| json!([&*l.pattern, &*l.color])) + .collect(); + json!({"t": "banner", "base": base, "layers": layers, "x0": x0, "y0": y0, "x1": x1, "y1": y1}) + } + ScreenDraw::Tooltip { key } => json!({"t": "tooltip", "key": key}), + ScreenDraw::SpriteOf { id } => { + json!({"t": "sprite_of", "id": id.trim_start_matches("minecraft:")}) + } + ScreenDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}), + ScreenDraw::Atlas { x0, y0, x1, y1, uv } => json!({ + "t": "atlas", "x0": x0, "y0": y0, "x1": x1, "y1": y1, + "u0": round(uv[0]), "u1": round(uv[1]), "v0": round(uv[2]), "v1": round(uv[3]) + }), + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: screen_layout_fixture RESOURCES INPUT OUTPUT"; + let banners = Banners::load(Path::new(args.get(1).ok_or(usage)?)); + let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let mut out = String::new(); + for line in input.lines().filter(|l| !l.trim().is_empty()) { + let c: Value = serde_json::from_str(line)?; + let int = |k: &str| c[k].as_i64().unwrap_or(0) as i32; + let draws = if c["screen"] == "loom" { + let patterns: Vec> = c["patterns"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p.as_str().map(Arc::from)) + .collect(); + let layers: Vec = c["resultLayers"] + .as_array() + .into_iter() + .flatten() + .map(|l| BannerLayer::new(l[0].as_str().unwrap_or(""), l[1].as_str().unwrap_or(""))) + .collect(); + let base = c["result"] + .as_str() + .and_then(banner_color) + .unwrap_or("white"); + let dye = c["dyeStack"] + .as_str() + .and_then(|d| d.strip_prefix("minecraft:")?.strip_suffix("_dye")) + .unwrap_or("white"); + let view = LoomView { + width: int("width"), + height: int("height"), + left: int("left"), + top: int("top"), + has_banner: c["banner"].is_string(), + has_dye: c["dye"].is_string(), + has_pattern: c["pattern"].is_string(), + patterns: &patterns, + selected: int("selected"), + display: c["display"].as_bool().unwrap_or(false), + has_max: c["hasMax"].as_bool().unwrap_or(false), + scroll: c["scroll"].as_f64().unwrap_or(0.0) as f32, + start_row: int("startRow") as usize, + result: c.get("resultLayers").map(|_| (base, layers.as_slice())), + dye, + mouse: (int("mouseX") as f32, int("mouseY") as f32), + }; + screen_layout::loom(&view, &banners) + } else { + let mut disabled = [false; 9]; + for (i, d) in c["disabled"] + .as_array() + .into_iter() + .flatten() + .enumerate() + .take(9) + { + disabled[i] = d.as_bool().unwrap_or(false); + } + screen_layout::crafter(&CrafterView { + width: int("width"), + height: int("height"), + left: int("left"), + top: int("top"), + disabled, + powered: c["powered"].as_bool().unwrap_or(false), + }) + }; + let list: Vec = draws.iter().map(draw_json).collect(); + out += &json!({ "draws": list }).to_string(); + out.push('\n'); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 561713d8a..759d6e0da 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -7,6 +7,7 @@ use horizon_client::{ banner::{self, BannerLayer}, hud::{HudBatch, Rect, rgba}, items::ItemStack, + screen_layout::{self, LoomView, ScreenDraw}, }; use std::sync::Arc; @@ -32,9 +33,6 @@ impl LoomState { fn offscreen_rows(&self) -> i32 { self.total_rows() as i32 - 4 } - fn scroll_active(&self) -> bool { - self.display && self.patterns.len() > 16 - } /// `startRow` for a scroller position. fn row_for(&self, offs: f32) -> usize { ((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize @@ -209,8 +207,116 @@ impl Game<'_> { ); } } - /// `LoomScreen.extractBackground` after the background; returns the - /// pattern name tooltip of the hovered button. + /// Paints `screen_layout` calls at the menu origin (ox, oy): the container + /// background and the dimmed world are drawn by the caller. + pub(super) fn paint_screen( + &self, + batch: &mut HudBatch, + ox: f32, + oy: f32, + draws: &[ScreenDraw], + background: bool, + ) -> Option> { + let atlas = &self.res.atlas; + let mut tooltip = None; + let mut sheet: Option = None; + for d in draws { + match d { + ScreenDraw::Gradient { .. } => {} + ScreenDraw::Blit { + texture, + x, + y, + w, + h, + tw, + th, + } => { + if background { + let name = texture + .trim_start_matches("textures/") + .trim_end_matches(".png"); + batch.sprite_region( + atlas, + name, + [ox + *x as f32, oy + *y as f32, *w as f32, *h as f32], + *tw as f32, + *th as f32, + ); + } + } + ScreenDraw::Sprite { id, x, y, .. } => batch.sprite( + atlas, + &format!("gui/sprites/{id}"), + ox + *x as f32, + oy + *y as f32, + ), + ScreenDraw::Banner { + base, + layers, + x0, + y0, + x1, + y1, + } => self.draw_flag( + batch, + [ + ox + *x0 as f32, + oy + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + ], + base, + layers, + ), + ScreenDraw::Tooltip { key } => { + tooltip = Some(vec![(self.translate(key, key), u32::MAX)]); + } + ScreenDraw::SpriteOf { id } => sheet = Some(id.clone()), + ScreenDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => { + let c = *color as u32; + batch.fill( + atlas, + ox + *x0 as f32, + oy + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8), + ); + } + ScreenDraw::Atlas { x0, y0, x1, y1, uv } => { + if let Some(r) = sheet.as_ref().and_then(|n| atlas.sprites.get(n)).copied() { + let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); + let part = Rect { + u0: r.u0 + uv[0] * du, + u1: r.u0 + uv[1] * du, + v0: r.v0 + uv[2] * dv, + v1: r.v0 + uv[3] * dv, + w: (x1 - x0) as u32, + h: (y1 - y0) as u32, + }; + batch.rect_uv( + ox + *x0 as f32, + oy + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + part, + u32::MAX, + ); + } + } + } + } + tooltip + } + /// `LoomScreen.extractBackground` after the background (the verified + /// `screen_layout::loom`); returns the hovered pattern's tooltip. pub(super) fn draw_loom( &mut self, batch: &mut HudBatch, @@ -220,102 +326,35 @@ impl Game<'_> { ) -> Option> { let s = self.station.as_ref()?; let l = &s.loom; - let atlas = &self.res.atlas; - for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() { - if s.inputs[i].is_none() { - let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i]; - batch.sprite( - atlas, - &format!("gui/sprites/container/slot/{icon}"), - ox + pos.0, - oy + pos.1, - ); - } - } - let scroller = if l.scroll_active() { - "scroller" - } else { - "scroller_disabled" - }; - batch.sprite( - atlas, - &format!("gui/sprites/container/loom/{scroller}"), - ox + 119.0, - oy + 13.0 + (41.0 * l.scroll).floor(), - ); - let result = s.result.clone(); - let (display, has_max, start_row, selected) = - (l.display, l.has_max, l.start_row, l.selected); - let patterns = l.patterns.clone(); let dye = s.inputs[1] .as_ref() - .and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d)) - .unwrap_or_else(|| Arc::from("white")); - if let Some(result) = result.filter(|_| !has_max) - && let Some(base) = banner::banner_color(&result.item) - { - self.draw_flag( - batch, - [ox + 141.0, oy + 8.0, 20.0, 40.0], - base, - banner::layers(&result), - ); - } else if has_max { - batch.sprite( - &self.res.atlas, - "gui/sprites/container/loom/error", - ox + 138.0, - oy + 52.0, - ); - } - let mut tooltip = None; - if display { - let atlas = &self.res.atlas; - for row in 0..4 { - for column in 0..4 { - let index = (row + start_row) * 4 + column; - let Some(pattern) = patterns.get(index) else { - return tooltip; - }; - let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); - let hover = inside(local, x, y, BUTTON, BUTTON); - let sprite = if selected == Some(index) { - "pattern_selected" - } else if hover { - let key = self - .res - .stations - .banners - .layer_key(&BannerLayer::new(pattern, &dye)); - tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]); - "pattern_highlighted" - } else { - "pattern" - }; - batch.sprite( - atlas, - &format!("gui/sprites/container/loom/{sprite}"), - ox + x, - oy + y, - ); - // extractBannerOnButton: a 5x10 grey cloth with the pattern. - batch.fill( - atlas, - ox + x + 4.0, - oy + y + 2.0, - 5.0, - 10.0, - dye_color("gray"), - ); - let texture = self.res.stations.banners.banner_texture(pattern); - if let Some(r) = atlas.sprites.get(&texture).copied() { - let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]); - batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX); - } - } - } - } - tooltip + .and_then(|d| self.res.items.get(&d.item)) + .and_then(|i| i.dye.clone()) + .unwrap_or_else(|| "white".to_owned()); + let result = s + .result + .as_ref() + .and_then(|r| Some((banner::banner_color(&r.item)?, banner::layers(r)))); + let view = LoomView { + width: 176, + height: 166, + left: 0, + top: 0, + has_banner: s.inputs[0].is_some(), + has_dye: s.inputs[1].is_some(), + has_pattern: s.inputs[2].is_some(), + patterns: &l.patterns, + selected: l.selected.map_or(-1, |i| i as i32), + display: l.display, + has_max: l.has_max, + scroll: l.scroll, + start_row: l.start_row, + result, + dye: &dye, + mouse: local, + }; + let draws = screen_layout::loom(&view, &self.res.stations.banners); + self.paint_screen(batch, ox, oy, &draws, false) } } @@ -334,7 +373,6 @@ mod tests { }; // 40 patterns = 10 rows, 6 off screen. assert_eq!(l.offscreen_rows(), 6); - assert!(l.scroll_active()); assert_eq!(l.row_for(0.0), 0); assert_eq!(l.row_for(1.0), 6); assert_eq!(l.row_for(0.5), 3); @@ -348,7 +386,6 @@ mod tests { display: true, ..Default::default() }; - assert!(!l.scroll_active()); assert_eq!(l.offscreen_rows(), 0); } } diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 32b28ad70..bd103bdfc 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -232,57 +232,42 @@ impl Game<'_> { _ => None, } } - /// `CrafterScreen`'s background, title, disabled slots and powered arrow. + /// `CrafterScreen`'s background, disabled slots and powered arrow (the + /// verified `screen_layout::crafter`) and its centred title. pub(in crate::game) fn draw_crafter_screen(&self, batch: &mut HudBatch, ox: f32, oy: f32) { let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else { return; }; + let powered = self + .container + .map(|k| self.world.block(k.0, k.1, k.2)) + .is_some_and(|state| self.containers().prop(state, "triggered") == Some("true")); + let draws = + horizon_client::screen_layout::crafter(&horizon_client::screen_layout::CrafterView { + width: 176, + height: 166, + left: 0, + top: 0, + disabled: c.disabled, + powered, + }); + // The background goes first, then the labels, then the slot decorations. + let (background, rest) = draws.split_at(2.min(draws.len())); + self.paint_screen(batch, ox, oy, background, true); let atlas = &self.res.atlas; - batch.sprite_region( - atlas, - "gui/container/crafter", - [ox, oy, 176.0, 166.0], - 256.0, - 256.0, - ); let grey = rgba(64, 64, 64, 255); let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); batch.text( atlas, &title, - ox + (176.0 - tw) / 2.0, + ox + ((176.0 - tw) / 2.0).trunc(), oy + 6.0, grey, false, ); batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); - for slot in 0..9 { - if c.disabled[slot] { - let (x, y) = self.crafter_slot_position(300 + slot).unwrap_or_default(); - batch.sprite( - atlas, - "gui/sprites/container/crafter/disabled_slot", - ox + x - 1.0, - oy + y - 1.0, - ); - } - } - let powered = self - .container - .map(|k| self.world.block(k.0, k.1, k.2)) - .is_some_and(|state| self.containers().prop(state, "triggered") == Some("true")); - let arrow = if powered { - "powered_redstone" - } else { - "unpowered_redstone" - }; - batch.sprite( - atlas, - &format!("gui/sprites/container/crafter/{arrow}"), - ox + 97.0, - oy + 35.0, - ); + self.paint_screen(batch, ox, oy, rest, true); } /// `gui.togglable_slot` over an empty, enabled grid slot. pub(in crate::game) fn crafter_tooltip(&self, slot: usize) -> Option { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index c3b63dca8..beb39729e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -87,6 +87,7 @@ pub mod save; pub mod scoreboard; pub mod scoreboard_cmd; pub mod screen_effects; +pub mod screen_layout; pub mod sculk; pub mod settings; pub mod shadows; diff --git a/crates/horizon-client/src/screen_layout.rs b/crates/horizon-client/src/screen_layout.rs new file mode 100644 index 000000000..c627e6b4a --- /dev/null +++ b/crates/horizon-client/src/screen_layout.rs @@ -0,0 +1,265 @@ +//! The loom and crafter screens' own drawing as `GuiGraphicsExtractor` calls: +//! `LoomScreen.extractBackground` (slot icons, the scroller, the pattern +//! buttons with their banner swatches and tooltip, the result banner or the +//! six-layer error) and `CrafterScreen`'s background, disabled slots and +//! redstone arrow. Computed without drawing so `tools/test_screen_layout_parity.py` +//! can compare them with the vanilla client; the game paints the same calls. +use crate::banner::{self, BannerLayer, Banners}; +use std::sync::Arc; + +/// One call a screen makes. +#[derive(Clone, Debug, PartialEq)] +pub enum ScreenDraw { + /// `fillGradient(0, 0, width, height, ..)`: the dimmed world behind a menu. + Gradient { x1: i32, y1: i32 }, + /// `blit(texture, x, y, 0, 0, w, h, tw, th)`: a container background. + Blit { + texture: &'static str, + x: i32, + y: i32, + w: i32, + h: i32, + tw: i32, + th: i32, + }, + /// `blitSprite(sprite, x, y, w, h)` of a GUI sprite. + Sprite { + id: String, + x: i32, + y: i32, + w: i32, + h: i32, + }, + /// `bannerPattern(flag, base, layers, x0, y0, x1, y1)`: the result preview. + Banner { + base: String, + layers: Vec, + x0: i32, + y0: i32, + x1: i32, + y1: i32, + }, + /// `setTooltipForNextFrame` with a translation key. + Tooltip { key: String }, + /// `getSprite(id)`: the atlas sprite the following `Atlas` blit uses. + SpriteOf { id: String }, + /// `fill(x0, y0, x1, y1, argb)`. + Fill { + x0: i32, + y0: i32, + x1: i32, + y1: i32, + color: i32, + }, + /// `blit(atlas, x0, y0, x1, y1, u0, u1, v0, v1)` with the UVs as fractions + /// of the sprite named by the last `SpriteOf`. + Atlas { + x0: i32, + y0: i32, + x1: i32, + y1: i32, + uv: [f32; 4], + }, +} + +/// What `LoomScreen.extractBackground` reads. +pub struct LoomView<'a> { + pub width: i32, + pub height: i32, + pub left: i32, + pub top: i32, + pub has_banner: bool, + pub has_dye: bool, + pub has_pattern: bool, + /// `menu.getSelectablePatterns()`. + pub patterns: &'a [Arc], + /// `menu.getSelectedBannerPatternIndex()`. + pub selected: i32, + pub display: bool, + pub has_max: bool, + pub scroll: f32, + pub start_row: usize, + /// The result banner's colour and layers (`resultBannerPatterns`). + pub result: Option<(&'a str, &'a [BannerLayer])>, + /// The dye stack's colour (`DataComponents.DYE`, white without one). + pub dye: &'a str, + pub mouse: (f32, f32), +} + +/// `DyeColor.getTextureDiffuseColor` as an opaque ARGB int. +fn diffuse(dye: &str) -> i32 { + (banner::dye_rgb(dye) | 0xFF00_0000) as i32 +} + +fn sprite(id: &str, x: i32, y: i32, w: i32, h: i32) -> ScreenDraw { + ScreenDraw::Sprite { + id: id.to_owned(), + x, + y, + w, + h, + } +} + +/// `LoomScreen.extractBackground`. +pub fn loom(v: &LoomView, banners: &Banners) -> Vec { + let (xo, yo) = (v.left, v.top); + let mut out = vec![ + ScreenDraw::Gradient { + x1: v.width, + y1: v.height, + }, + ScreenDraw::Blit { + texture: "textures/gui/container/loom.png", + x: xo, + y: yo, + w: 176, + h: 166, + tw: 256, + th: 256, + }, + ]; + for (has, icon, x, y) in [ + (v.has_banner, "banner", 13, 26), + (v.has_dye, "dye", 33, 26), + (v.has_pattern, "banner_pattern", 23, 45), + ] { + if !has { + out.push(sprite( + &format!("container/slot/{icon}"), + xo + x, + yo + y, + 16, + 16, + )); + } + } + let sy = (41.0 * v.scroll) as i32; + let active = v.display && v.patterns.len() > 16; + out.push(sprite( + if active { + "container/loom/scroller" + } else { + "container/loom/scroller_disabled" + }, + xo + 119, + yo + 13 + sy, + 12, + 15, + )); + match v.result { + Some((base, layers)) if !v.has_max => out.push(ScreenDraw::Banner { + base: base.to_owned(), + layers: layers.to_vec(), + x0: xo + 141, + y0: yo + 8, + x1: xo + 161, + y1: yo + 48, + }), + _ if v.has_max => out.push(sprite("container/loom/error", xo + 138, yo + 52, 26, 26)), + _ => {} + } + if v.display { + let (x, y) = (xo + 60, yo + 13); + 'rows: for row in 0..4 { + for column in 0..4 { + let index = (row + v.start_row) * 4 + column; + let Some(pattern) = v.patterns.get(index) else { + break 'rows; + }; + let (px, py) = (x + column as i32 * 14, y + row as i32 * 14); + let (mx, my) = v.mouse; + let highlighted = mx >= px as f32 + && my >= py as f32 + && mx < (px + 14) as f32 + && my < (py + 14) as f32; + let button = if index as i32 == v.selected { + "container/loom/pattern_selected" + } else if highlighted { + out.push(ScreenDraw::Tooltip { + key: banners.layer_key(&BannerLayer::new(pattern, v.dye)), + }); + "container/loom/pattern_highlighted" + } else { + "container/loom/pattern" + }; + out.push(sprite(button, px, py, 14, 14)); + // extractBannerOnButton: a grey 5x10 swatch with the pattern's front. + out.push(ScreenDraw::SpriteOf { + id: banners.banner_texture(pattern), + }); + let (bx, by) = (px + 4, py + 2); + out.push(ScreenDraw::Fill { + x0: bx, + y0: by, + x1: bx + 5, + y1: by + 10, + color: diffuse("gray"), + }); + let v0 = 1.0 / 64.0; + out.push(ScreenDraw::Atlas { + x0: bx, + y0: by, + x1: bx + 5, + y1: by + 10, + uv: [0.0, 21.0 / 64.0, v0, v0 + 40.0 / 64.0], + }); + } + } + } + out +} + +/// What `CrafterScreen` draws besides the generic container parts. +pub struct CrafterView { + pub width: i32, + pub height: i32, + pub left: i32, + pub top: i32, + pub disabled: [bool; 9], + pub powered: bool, +} + +/// `CrafterScreen.extractBackground`, the disabled slots of `extractSlot` +/// and `extractRedstone`. +pub fn crafter(v: &CrafterView) -> Vec { + let mut out = vec![ + ScreenDraw::Gradient { + x1: v.width, + y1: v.height, + }, + ScreenDraw::Blit { + texture: "textures/gui/container/crafter.png", + x: (v.width - 176) / 2, + y: (v.height - 166) / 2, + w: 176, + h: 166, + tw: 256, + th: 256, + }, + ]; + for (i, disabled) in v.disabled.iter().enumerate() { + if *disabled { + let (x, y) = (26 + (i % 3) as i32 * 18, 17 + (i / 3) as i32 * 18); + out.push(sprite( + "container/crafter/disabled_slot", + v.left + x - 1, + v.top + y - 1, + 18, + 18, + )); + } + } + out.push(sprite( + if v.powered { + "container/crafter/powered_redstone" + } else { + "container/crafter/unpowered_redstone" + }, + v.width / 2 + 9, + v.height / 2 - 48, + 16, + 16, + )); + out +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java new file mode 100644 index 000000000..105329c1d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java @@ -0,0 +1,282 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.renderpearl.api.pipeline.RenderPipeline; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.gui.screens.inventory.CrafterScreen; +import net.minecraft.client.gui.screens.inventory.LoomScreen; +import net.minecraft.client.model.object.banner.BannerFlagModel; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.sprite.SpriteId; +import net.minecraft.core.Holder; +import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.level.block.entity.BannerPatternLayers; +import org.joml.Matrix3x2fStack; + +/** + * Original oracle for the loom and crafter screens' own drawing: vanilla's + * LoomScreen.extractBackground (slot icons, scroller, pattern buttons with + * their banner swatches and tooltips, the result banner or the six-layer + * error) and CrafterScreen's background, disabled slots and redstone arrow, + * on screens and menus whose fields come from the case, recording every + * GuiGraphicsExtractor call they make. + */ +public final class VanillaLoomScreenOracle { + static Object unsafe; + static Method allocate; + static JsonObject c; + + @SuppressWarnings("unchecked") + static T alloc(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static void put(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f); + Class t = f.getType(); + String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject"; + Class param = t.isPrimitive() ? t : Object.class; + unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value); + } + + static net.minecraft.client.Minecraft mc; + + /** A stand-in client: Screen.extractBackground only asks its HUD for deferred subtitles (none). */ + static net.minecraft.client.Minecraft minecraft() throws Exception { + if (mc == null) { + mc = alloc(net.minecraft.client.Minecraft.class); + var gui = alloc(net.minecraft.client.gui.Gui.class); + put(gui, net.minecraft.client.gui.Gui.class, "hud", alloc(net.minecraft.client.gui.Hud.class)); + put(mc, net.minecraft.client.Minecraft.class, "gui", gui); + } + return mc; + } + + static float round(float v) { + return Math.round(v * 1e6f) / 1e6f; + } + + /** Records the screens' GuiGraphicsExtractor calls. */ + public static final class Capture extends GuiGraphicsExtractor { + JsonArray draws; + Matrix3x2fStack stack; + Map names = new IdentityHashMap<>(); + private Capture() { super(null, null, 0, 0); } + @Override public int guiWidth() { return c.get("width").getAsInt(); } + @Override public int guiHeight() { return c.get("height").getAsInt(); } + @Override public Matrix3x2fStack pose() { return stack; } + @Override public void nextStratum() { } + @Override public void requestCursor(com.mojang.blaze3d.platform.cursor.CursorType type) { } + JsonObject add(String type) { + var o = new JsonObject(); + o.addProperty("t", type); + draws.add(o); + return o; + } + int tx(int x) { return x + Math.round(stack.m20()); } + int ty(int y) { return y + Math.round(stack.m21()); } + @Override public void fillGradient(int x0, int y0, int x1, int y1, int c1, int c2) { + var o = add("gradient"); + o.addProperty("x1", x1); o.addProperty("y1", y1); + } + @Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) { + var o = add("fill"); + o.addProperty("x0", tx(Math.min(x0, x1))); o.addProperty("y0", ty(Math.min(y0, y1))); + o.addProperty("x1", tx(Math.max(x0, x1))); o.addProperty("y1", ty(Math.max(y0, y1))); + o.addProperty("color", color); + } + @Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { + var o = add("sprite"); + o.addProperty("id", id.getPath()); + o.addProperty("x", tx(x)); o.addProperty("y", ty(y)); o.addProperty("w", w); o.addProperty("h", h); + } + @Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int srcW, int srcH, int texW, int texH, int color) { + var o = add("blit"); + o.addProperty("texture", texture.getPath()); + o.addProperty("x", tx(x)); o.addProperty("y", ty(y)); o.addProperty("w", w); o.addProperty("h", h); + o.addProperty("u", u); o.addProperty("v", v); o.addProperty("tw", texW); o.addProperty("th", texH); + } + @Override public void blit(Identifier location, int x0, int y0, int x1, int y1, float u0, float u1, float v0, float v1) { + var o = add("atlas"); + o.addProperty("x0", tx(x0)); o.addProperty("y0", ty(y0)); o.addProperty("x1", tx(x1)); o.addProperty("y1", ty(y1)); + o.addProperty("u0", round(u0)); o.addProperty("u1", round(u1)); o.addProperty("v0", round(v0)); o.addProperty("v1", round(v1)); + } + /** A stand-in sprite spanning the whole texture: the UVs a screen picks are then fractions of it. */ + @Override public TextureAtlasSprite getSprite(SpriteId id) { + try { + TextureAtlasSprite s = alloc(TextureAtlasSprite.class); + put(s, TextureAtlasSprite.class, "atlasLocation", id.atlasLocation()); + put(s, TextureAtlasSprite.class, "u0", 0f); + put(s, TextureAtlasSprite.class, "u1", 1f); + put(s, TextureAtlasSprite.class, "v0", 0f); + put(s, TextureAtlasSprite.class, "v1", 1f); + var o = add("sprite_of"); + o.addProperty("id", id.texture().getPath()); + return s; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + @Override public void bannerPattern(BannerFlagModel flag, DyeColor base, BannerPatternLayers layers, int x0, int y0, int x1, int y1) { + var o = add("banner"); + o.addProperty("base", base.getSerializedName()); + var a = new JsonArray(); + for (var layer : layers.layers()) { + var l = new JsonArray(); + l.add(layer.pattern().unwrapKey().orElseThrow().identifier().toString()); + l.add(layer.color().getSerializedName()); + a.add(l); + } + o.add("layers", a); + o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1); + } + @Override public void setTooltipForNextFrame(Component text, int x, int y) { + var o = add("tooltip"); + o.addProperty("key", text.getContents() instanceof TranslatableContents t ? t.getKey() : text.getString()); + } + } + + static Holder pattern(String id) { + return ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN).getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(id))); + } + + static BannerPatternLayers layers(JsonArray list) { + var b = new BannerPatternLayers.Builder(); + for (var l : list) { + var p = l.getAsJsonArray(); + b.add(pattern(p.get(0).getAsString()), DyeColor.byName(p.get(1).getAsString(), DyeColor.WHITE)); + } + return b.build(); + } + + static Slot slot(String item, int x, int y) { + var container = new SimpleContainer(1); + if (item != null) container.setItem(0, new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(item)))); + return new Slot(container, 0, x, y); + } + + static String opt(String key) { + return c.has(key) && !c.get(key).isJsonNull() ? c.get(key).getAsString() : null; + } + + static void loom(Capture g) throws Exception { + LoomMenu menu = alloc(LoomMenu.class); + put(menu, LoomMenu.class, "bannerSlot", slot(opt("banner"), 13, 26)); + put(menu, LoomMenu.class, "dyeSlot", slot(opt("dye"), 33, 26)); + put(menu, LoomMenu.class, "patternSlot", slot(opt("pattern"), 23, 45)); + put(menu, LoomMenu.class, "resultSlot", slot(opt("result"), 143, 57)); + List> patterns = new ArrayList<>(); + for (var p : c.getAsJsonArray("patterns")) patterns.add(pattern(p.getAsString())); + put(menu, LoomMenu.class, "selectablePatterns", patterns); + DataSlot selected = DataSlot.standalone(); + selected.set(c.get("selected").getAsInt()); + put(menu, LoomMenu.class, "selectedBannerPatternIndex", selected); + LoomScreen screen = alloc(LoomScreen.class); + put(screen, net.minecraft.client.gui.screens.Screen.class, "minecraft", minecraft()); + put(screen, AbstractContainerScreen.class, "menu", menu); + put(screen, AbstractContainerScreen.class, "imageWidth", 176); + put(screen, AbstractContainerScreen.class, "imageHeight", 166); + put(screen, AbstractContainerScreen.class, "leftPos", c.get("left").getAsInt()); + put(screen, AbstractContainerScreen.class, "topPos", c.get("top").getAsInt()); + put(screen, net.minecraft.client.gui.screens.Screen.class, "width", c.get("width").getAsInt()); + put(screen, net.minecraft.client.gui.screens.Screen.class, "height", c.get("height").getAsInt()); + put(screen, LoomScreen.class, "displayPatterns", c.get("display").getAsBoolean()); + put(screen, LoomScreen.class, "hasMaxPatterns", c.get("hasMax").getAsBoolean()); + put(screen, LoomScreen.class, "scrollOffs", c.get("scroll").getAsFloat()); + put(screen, LoomScreen.class, "startRow", c.get("startRow").getAsInt()); + put(screen, LoomScreen.class, "resultBannerPatterns", c.has("resultLayers") ? layers(c.getAsJsonArray("resultLayers")) : null); + ItemStack dye = opt("dyeStack") == null ? ItemStack.EMPTY : new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(opt("dyeStack")))); + put(screen, LoomScreen.class, "dyeStack", dye); + try { + screen.extractBackground(g, c.get("mouseX").getAsInt(), c.get("mouseY").getAsInt(), 0f); + } catch (NullPointerException e) { + // Lighting setup for the items after the background: no game renderer here. + if (System.getenv("ORACLE_TRACE") != null) e.printStackTrace(); + } + } + + static void crafter(Capture g) throws Exception { + CrafterMenu menu = alloc(CrafterMenu.class); + var data = new SimpleContainerData(10); + var disabled = c.getAsJsonArray("disabled"); + for (int i = 0; i < 9; i++) data.set(i, disabled.get(i).getAsBoolean() ? 1 : 0); + data.set(9, c.get("powered").getAsBoolean() ? 1 : 0); + put(menu, CrafterMenu.class, "containerData", data); + CrafterScreen screen = alloc(CrafterScreen.class); + put(screen, net.minecraft.client.gui.screens.Screen.class, "minecraft", minecraft()); + put(screen, AbstractContainerScreen.class, "menu", menu); + put(screen, AbstractContainerScreen.class, "imageWidth", 176); + put(screen, AbstractContainerScreen.class, "imageHeight", 166); + int left = c.get("left").getAsInt(), top = c.get("top").getAsInt(); + put(screen, AbstractContainerScreen.class, "leftPos", left); + put(screen, AbstractContainerScreen.class, "topPos", top); + put(screen, net.minecraft.client.gui.screens.Screen.class, "width", c.get("width").getAsInt()); + put(screen, net.minecraft.client.gui.screens.Screen.class, "height", c.get("height").getAsInt()); + screen.extractBackground(g, 0, 0, 0f); + // AbstractContainerScreen.extractSlots: the slots under the menu's offset. + g.stack.pushMatrix(); + g.stack.translate(left, top); + Method extractSlot = CrafterScreen.class.getDeclaredMethod("extractSlot", GuiGraphicsExtractor.class, Slot.class, int.class, int.class); + extractSlot.setAccessible(true); + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + int i = x + y * 3; + if (!disabled.get(i).getAsBoolean()) continue; + var slot = new CrafterSlot(new SimpleContainer(9), i, 26 + x * 18, 17 + y * 18, menu); + put(slot, Slot.class, "index", i); + extractSlot.invoke(screen, g, slot, -100, -100); + } + } + g.stack.popMatrix(); + Method redstone = CrafterScreen.class.getDeclaredMethod("extractRedstone", GuiGraphicsExtractor.class); + redstone.setAccessible(true); + redstone.invoke(screen, g); + } + + 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); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + try { + var g = alloc(Capture.class); + g.draws = new JsonArray(); + g.stack = new Matrix3x2fStack(16); + put(g, GuiGraphicsExtractor.class, "pose", g.stack); + if (c.get("screen").getAsString().equals("loom")) loom(g); else crafter(g); + result.add("draws", g.draws); + } catch (Throwable e) { + Throwable t = e instanceof InvocationTargetException ite ? ite.getCause() : e; + result.addProperty("error", t.toString()); + if (System.getenv("ORACLE_TRACE") != null) t.printStackTrace(); + } + out.append(result).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_screen_layout_parity.py b/tools/test_screen_layout_parity.py new file mode 100644 index 000000000..d488716f6 --- /dev/null +++ b/tools/test_screen_layout_parity.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Compare the loom and crafter screens' drawing with the vanilla client's. + +The Java oracle (VanillaLoomScreenOracle) runs LoomScreen.extractBackground on +a loom screen and menu whose state comes from the case (inputs present, the +selectable patterns, the selected one, the scroller, the result banner or +the six-layer error, the mouse over a pattern button) and CrafterScreen's +background, disabled slots and redstone arrow, recording every +GuiGraphicsExtractor call; examples/screen_layout_fixture lays out the same +state with horizon_client::screen_layout, which the game paints. The ordered +call lists must agree. +""" +import argparse +import json +import os +import random +import subprocess +import sys +try: + from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base +except ImportError: + import interaction_lab as lib + import test_model_baking_parity as baking + import test_rust_parity as base + +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def no_item_required(): + root = lib.RESOURCES / 'data/minecraft/tags/banner_pattern' + out = [] + for v in json.loads((root / 'no_item_required.json').read_text())['values']: + out.append(v) + return out + + +def cases(count, seed): + rng = random.Random(seed) + common = no_item_required() + special = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json')) + out = [] + for n in range(count): + width = rng.choice([320, 427, 480, 640, 961, 175]) + height = rng.choice([240, 255, 360, 501, 165]) + left, top = (width - 176) // 2, (height - 166) // 2 + if n % 4 == 3: + out.append({'screen': 'crafter', 'width': width, 'height': height, 'left': left, 'top': top, + 'disabled': [rng.random() < 0.3 for _ in range(9)], 'powered': rng.random() < 0.5}) + continue + patterns = rng.choice([common, common, [rng.choice(special)], rng.sample(special, 3), []]) + rows = -(-len(patterns) // 4) + scroll = rng.choice([0.0, 0.0, 1.0, round(rng.random(), 4)]) + start = max(int(scroll * max(rows - 4, 0) + 0.5), 0) if rng.random() < 0.8 else rng.randrange(0, max(rows, 1)) + case = {'screen': 'loom', 'width': width, 'height': height, 'left': left, 'top': top, + 'banner': rng.choice(['minecraft:white_banner', 'minecraft:red_banner', None]), + 'dye': rng.choice(['minecraft:red_dye', 'minecraft:blue_dye', None]), + 'pattern': rng.choice(['minecraft:creeper_banner_pattern', None, None]), + 'patterns': patterns, 'selected': rng.choice([-1, 0, 1, 5, 20, len(patterns) - 1]), + 'display': rng.random() < 0.75, 'hasMax': rng.random() < 0.15, 'scroll': scroll, 'startRow': start, + 'dyeStack': rng.choice(['minecraft:%s_dye' % rng.choice(DYES), None]), + 'mouseX': left + 60 + rng.randrange(-3, 60), 'mouseY': top + 13 + rng.randrange(-3, 60)} + if rng.random() < 0.6: + case['result'] = 'minecraft:%s_banner' % rng.choice(DYES) + case['resultLayers'] = [[rng.choice(common), rng.choice(DYES)] for _ in range(rng.choice([1, 2, 6, 7]))] + out.append(case) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--count', type=int, default=1600) + parser.add_argument('--seed', type=int, default=3) + parser.add_argument('--detail', type=int, default=2) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + work = lib.work_dir('screen-layout-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + chosen = cases(args.count, args.seed) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps, + '-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'VanillaLoomScreenOracle'))], + capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaLoomScreenOracle', + str(work / 'cases.jsonl'), str(work / 'native.jsonl')], capture_output=True, text=True) + if run.returncode: + print(run.stderr[-4000:]) + sys.exit('oracle failed') + lib.cargo_example('horizon-client', 'screen_layout_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.jsonl') + native = [json.loads(l) for l in (work / 'native.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()] + assert len(native) == len(rust) == len(chosen) + bad, errors = {}, 0 + for case, a, b in zip(chosen, native, rust): + if 'error' in a: + errors += 1 + print('oracle error', a['error']) + continue + if a['draws'] != b['draws']: + bad.setdefault(case['screen'], []).append((case, a['draws'], b['draws'])) + for screen, entries in bad.items(): + print(f'{screen}: {len(entries)} differing') + for case, a, b in entries[:args.detail]: + i = next((k for k, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b))) + print(' case ', json.dumps(case)[:400]) + print(' native', a[i] if i < len(a) else '-') + print(' rust ', b[i] if i < len(b) else '-') + total = sum(len(v) for v in bad.values()) + print(f'{len(chosen) - total - errors}/{len(chosen)} screens match ({errors} oracle errors)') + raise SystemExit(1 if total or errors else 0) + + +if __name__ == '__main__': + main() From 05228e0fe2ca07dedfff0f4181a2c68929bfced8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:39:45 +0200 Subject: [PATCH 7/7] Document the loom, crafter and recipe book harnesses Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- docs/rust-parity.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c8ae1d65c..33456b150 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Horizon is a Rust rewrite of Minecraft Java **26.3** targeting one-to-one vanill - shields, maps, books, fireworks, beacons, advancements and statistics; - Anvil saves. -Parity is **not** complete. Still missing: the warden and the sculk family, the breeze, sniffer, creaking, happy ghast, llamas and a few other mobs, raids and pillager patrols, villager breeding and gossip, the loom, crafter and recipe book, scoreboards, subtitles, and spawned mob gear enchantments. Multiplayer joins vanilla servers but Horizon cannot host one. See [Rust rewrite status](docs/rust-parity.md). +Parity is **not** complete. Still missing: the warden and the sculk family, the breeze, sniffer, creaking, happy ghast, llamas and a few other mobs, raids and pillager patrols, villager breeding and gossip, scoreboards, subtitles, and spawned mob gear enchantments. Multiplayer joins vanilla servers but Horizon cannot host one. See [Rust rewrite status](docs/rust-parity.md). ### Java parity: 84% @@ -39,10 +39,10 @@ round-trip harness has not been rerun. | World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla | | Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.18.2 to 26.2 upgrade as vanilla's DataFixers do over 22 sample worlds; worlds older than 1.18.2 are not upgraded | | Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules and natural spawning (15,500 NaturalSpawner cases) match; AI not compared; drowned, villagers, traders and the wither unverified | -| Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences | +| Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla | | Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering | | Audio | 0.75 | Sound engine, music and ambience not compared with vanilla | -| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone and dispensers match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems | +| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone, dispensers and crafters (4,000 crafts) match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems | ### Next steps diff --git a/docs/rust-parity.md b/docs/rust-parity.md index 807b875cb..751ebec41 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1288,3 +1288,48 @@ binding. Rendering, transport, full entity lifecycle integration and playable Linux gameplay remain unfinished. In this pinned version, `LivingEntity.updateDataBeforeSync` invokes dirty effect synchronization; it is a separate phase from `tickEffects`. + +## Loom, crafter and recipe book + +The loom, the crafter and the recipe book run on code checked against +vanilla's own classes, and the game uses that code: + +- **Menus.** `horizon_client::menu` runs `LoomMenu` (selectable patterns, + `clickMenuButton`, the six-layer limit, quick moves, the result's `onTake`) + and the server's `CrafterMenu` over the block entity (the result following + the grid, `setSlotState`, a filled disabled slot enabling itself) besides the + other menus. `tools/test_menu_click_parity.py` compares 8,000 random click + sequences over 19 menus, with pattern button and slot state packets, with + vanilla's menu classes. The game's loom and crafter screens click through + `Game::menu_session` on the same engine. +- **Crafter block.** `tools/test_crafter_parity.py` runs `CrafterBlock.dispenseFrom` + and `CrafterBlockEntity.serverTick` over the block update oracle's level: + 4,000 crafts of datapack recipes (remainders and special recipes included) + with disabled slots and containers, other crafters or air in front, comparing + block changes, container contents, the animation ticks, triggered flag, + comparator signal, shot items, level events and the level random. +- **Recipe placement.** `horizon_client::menu::place` ports `ServerPlaceRecipe` + with `StackedContents`' recipe picker for the inventory, crafting table and + furnaces. 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; `tools/test_place_recipe_parity.py` + hands the oracle's order to the Rust side and compares 6,000 placements. +- **The book's contents.** `recipe_book::ClientBook` keeps the displays as + `ClientRecipeBook`'s `HashMap` of display ids does (on the verified Java + `HashMap` port), whose order is the order of the buttons; + `tools/test_recipe_book_view_parity.py` runs the client's `ClientRecipeBook`, + `RecipeCollection` selection and the tab and page logic over 1,200 cases. +- **The player's book.** `recipe_book::Settings` with a `RecipeIndex` is + `ServerRecipeBook`: awards (advancements, `/recipe`, crafting) never learn + special recipes and count displays, and loading drops unknown recipes; + `tools/test_recipe_book_parity.py` compares 1,500 operation sequences and the + saved compound. +- **Screens.** `screen_layout` holds `LoomScreen.extractBackground` and + `CrafterScreen`'s decorations as draw calls the game paints; + `tools/test_screen_layout_parity.py` runs vanilla's screens on stand-in + menus and compares 1,600 call lists. + +Not compared yet: the recipe book's own drawing (tabs, buttons, the overlay +and ghost slots) and its text search, the banner preview's 3D flag (drawn as +the flat front face), furnaces awarding their recipes and experience when +their output is taken, and the limited crafting game rule.