From 80645bf0de2fdd28a80a158e35c06436dba49653 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:43:24 +0200 Subject: [PATCH] Sweet berries, carrots and potatoes are planted instead of eaten A right click with food that is also a block item tried to eat it before placing it: in creative always, in survival whenever the player was hungry. BlockItem.useOn places first and only eats a consumable that could not be placed (counting the use, as ItemStack.useOn does). Picking a sweet berry bush or cave vines dropped nothing: the harvest loot (Block.dropFromBlockInteractLootTable) is now rolled and popped. Bone meal on a bush that can still grow grows it (SweetBerryBushBlock.useItemOn passes it on) instead of picking it, and counts the use with its item_interact_finish vibration. Every block placement played its sound twice; BlockItem.place's level event is now the only one. tools/test_use_item_on_parity.py drives vanilla's real ServerPlayerGameMode.useItemOn (and Minecraft.startUseItem's useItem fallback) against use_item_as_player in a headless game. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 75 ++++++---- .../src/game/dispense_fixture.rs | 71 +++++++++ crates/horizon-client/src/game/growth.rs | 11 ++ crates/horizon-client/src/game/spill.rs | 17 +++ crates/horizon-client/src/items.rs | 27 ++++ crates/horizon-world/src/level/interact.rs | 24 ++++ .../parity/VanillaDispenserOracle.java | 89 ++++++++++++ tools/test_use_item_on_parity.py | 136 ++++++++++++++++++ 8 files changed, 423 insertions(+), 27 deletions(-) create mode 100644 tools/test_use_item_on_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 483646a90..e2ae1223b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -519,6 +519,13 @@ impl LevelAccess for GameLevel<'_> { effect: PlayerEffect::DropItem(item), .. } => self.pop_above(pos, item), + // Picking a sweet berry bush or cave vines: the harvest loot, + // popped before the pick sound draws its pitch. + LevelEvent::Player { + pos, + state, + effect: PlayerEffect::InteractLoot(table), + } => self.drop_interact_loot(pos, state, table), event => self.events.push(event), } } @@ -2109,14 +2116,16 @@ impl Game<'_> { game_master: false, }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let item = held.as_ref().map(|s| s.item.to_string()); let result = self.with_level(|b, level, ticks| { - b.use_without_item( + b.use_item_on( level, ticks, BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), face, at, player, + item.as_deref(), ) }); self.process_level_events()?; @@ -2158,14 +2167,10 @@ impl Game<'_> { } return Ok(()); } - if info.food.is_some() - && let Some(p) = self.player.as_ref() - && (p.health.food.food < 20 || self.creative) - { - // Consumable.startConsuming: held right click for consume_seconds. - if self.using.is_none() { - self.using = Some((self.selected, 0)); - } + // Food that is also a block item (berries, carrots, potatoes) aimed at + // a block tries to place first: BlockItem.useOn eats only when the + // placement fails. + if !(info.block.is_some() && self.pick().is_some()) && self.start_eating(&info) { return Ok(()); } if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? { @@ -2198,6 +2203,8 @@ impl Game<'_> { return Ok(()); } if !self.may_build() { + // ItemStack.useOn passes in adventure mode; useItem eats. + self.start_eating(&info); return Ok(()); } let face = match hit.face { @@ -2223,6 +2230,11 @@ impl Game<'_> { let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx)); let PlaceOutcome::Placed { pos, state } = outcome else { self.process_level_events()?; + // BlockItem.useOn: a consumable that could not be placed is used, + // which ItemStack.useOn counts as a use of the item. + if self.start_eating(&info) { + self.stats.add("used", &stack.item, 1); + } return Ok(()); }; let target = [pos.x, pos.y, pos.z]; @@ -2239,25 +2251,18 @@ impl Game<'_> { } } self.swing_arm(); - let sounds = self.res.facts.get(state).sounds.clone(); - let center = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]) + 0.5, - f64::from(target[2]) + 0.5, - ]; - // SolidBucketItem.getPlaceSound: the bucket's own empty sound. + // BlockItem.place's sound is among the level events; + // SolidBucketItem.getPlaceSound replaces it with the bucket's own. let solid_bucket = &*stack.item == "minecraft:powder_snow_bucket"; - let place_sound = if solid_bucket { - "minecraft:item.bucket.empty_powder_snow" - } else { - &sounds.place - }; - self.audio.play( - place_sound, - Some(center), - (sounds.volume + 1.0) / 2.0, - sounds.pitch * 0.8, - ); + if solid_bucket { + for event in &mut self.level_events { + if let LevelEvent::Sound { pos: at, sound, .. } = event + && *at == pos + { + *sound = "minecraft:item.bucket.empty_powder_snow".into(); + } + } + } self.process_level_events()?; // BlockItem.place: the used statistic and the placed_block trigger. self.stats.add("used", &stack.item, 1); @@ -2271,6 +2276,22 @@ impl Game<'_> { } Ok(()) } + /// `Consumable.startConsuming` for held food the player can eat + /// (`Player.canEat`): the right click is held for `consume_seconds`. + fn start_eating(&mut self, info: &horizon_client::items::ItemInfo) -> bool { + if info.food.is_none() + || !self + .player + .as_ref() + .is_some_and(|p| p.health.food.food < 20 || self.creative) + { + return false; + } + if self.using.is_none() { + self.using = Some((self.selected, 0)); + } + true + } fn consume_held(&mut self) { if self.creative { return; diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index c92f88505..e3fd0e896 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -10,11 +10,13 @@ use super::{ use horizon_client::{ Result, chunk::Chunk, + command::args::GameMode, containers::BlockEntity, gamerules::Value as RuleValue, item_data::{canon_stack, parse_stack}, items::ItemStack, mobs::{Mob, Species}, + motion::PlayerMotion, projectiles::ProjectileKind, world::World, }; @@ -25,6 +27,7 @@ use horizon_core::{ use horizon_world::{level::Ticks, registry::BlockStateId}; use serde_json::Value; use std::{cell::RefCell, collections::HashMap, fmt::Write as _, io::Write as _, sync::Arc}; +use winit::keyboard::KeyCode; thread_local! { /// Level and game events recorded while a fixture case runs. @@ -267,6 +270,8 @@ impl Game<'_> { self.fixture_remove(origin, op)?; } else if let Some(op) = case.get("use") { used = self.fixture_use(origin, op)?; + } else if let Some(op) = case.get("use_item") { + used = self.fixture_use_item(origin, op)?; } else if case.get("hopper").is_some() { // HopperBlockEntity.pushItemsTick, once. self.hopper_try_move_items((origin.x, origin.y, origin.z)); @@ -402,6 +407,72 @@ impl Game<'_> { Ok(out) } + /// A player three blocks south of `pos` right-clicks its top face holding + /// the case's item (`use_item_as_player` on that hit): the statistics, + /// the held stack and the item it started using, as + /// `VanillaDispenserOracle.useItem` prints them. + fn fixture_use_item(&mut self, pos: BlockPos, op: &Value) -> Result> { + let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?; + self.mode = if op["creative"].as_bool().unwrap_or(false) { + GameMode::Creative + } else { + GameMode::Survival + }; + self.creative = self.mode == GameMode::Creative; + let mut player = PlayerMotion::new( + self.motion, + horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 3.5, + ), + )?; + player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32; + self.player = Some(player); + self.yaw = 0.0; + self.pitch = 90.0; + self.keys.clear(); + if op["sneaking"].as_bool().unwrap_or(false) { + self.keys.insert(KeyCode::ShiftLeft); + } + self.using = None; + self.inventory[self.selected] = stack.clone(); + let used_before = stack + .as_ref() + .map_or(0, |s| self.stats.get("used", &s.item)); + self.forced_hit = Some(super::Hit { + pos: [pos.x, pos.y, pos.z], + face: [0, 1, 0], + point: [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 0.5, + ], + }); + let used = self.use_item_as_player(); + self.forced_hit = None; + used?; + self.process_level_events()?; + let mut out = Vec::new(); + if let Some(s) = &stack { + let used = self.stats.get("used", &s.item) - used_before; + if used != 0 { + out.push(format!("stat {} minecraft:used {used}", s.item)); + } + } + let using = self + .using + .and_then(|(slot, _)| self.stack_in(slot)) + .map_or("-".to_owned(), |s| s.item.to_string()); + out.push(format!( + "held {} using {using}", + canon_stack(self.inventory[self.selected].as_ref()) + )); + self.player = None; + self.using = None; + Ok(out) + } + /// A stack in a block entity's slot: a container's, a jukebox's record, a /// lectern's book, or the items of a block entity Horizon keeps as saved. fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index a53d0ac69..7e5ad08ce 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -47,9 +47,20 @@ impl Game<'_> { }; let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]); let used = self.with_level(|b, level, ticks| b.use_bone_meal(level, ticks, pos, face)); + // ItemStack.causeUseVibration at the player, after the meal is used + // up (shrunk even in creative): an emptied stack has no use effects. + if used + && stack.count > 1 + && let Some(p) = self.player.as_ref().map(|p| p.position) + { + let ctx = self.player_context(None); + self.post_game_event("minecraft:item_interact_finish", [p.x, p.y, p.z], ctx); + } self.process_level_events()?; if used { self.swing_arm(); + // ItemStack.useOn: an item interaction counts as a use. + self.stats.add("used", &stack.item, 1); self.consume_held(); } Ok(used) diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index 3e910ca1f..9e4ccdf76 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -221,6 +221,23 @@ impl GameLevel<'_> { delay: 10, }); } + /// `Block.dropFromBlockInteractLootTable` with `Block.popResource` of + /// every stack. + pub(super) fn drop_interact_loot(&mut self, pos: BlockPos, state: BlockStateId, table: &str) { + let drops = self.items.interact_loot( + table, + self.registry, + state, + &mut self.world.random, + self.rand_sequences, + self.seed, + ); + for stack in drops { + if &*stack.item != "minecraft:air" && stack.count > 0 { + self.pop_resource([pos.x, pos.y, pos.z], stack); + } + } + } /// `Block.dropResources(state, level, pos, blockEntity)`: the block's loot /// (from its random sequence, else the level random), with what its block /// entity copies into it, popped at once. diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8a71b77ab..9892243fc 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -754,6 +754,33 @@ impl Items { .as_str() .map(str::to_owned) } + /// `Block.dropFromBlockInteractLootTable`: the `block_interact` table `id` + /// for a right click on `state` (its `match_block` conditions see the + /// state), from the table's random sequence when it has one. + pub fn interact_loot( + &self, + id: &str, + registry: &BlockRegistry, + state: BlockStateId, + random: &mut impl RandomSource, + sequences: &mut crate::random_sequences::RandomSequences, + seed: i64, + ) -> Vec { + let (Some(table), Some(block)) = (self.loot.get(id), registry.state(state)) else { + return vec![]; + }; + let ctx = LootContext { + items: self, + block: &block.name, + properties: &block.properties, + held: None, + killed_by_player: false, + }; + match table.get("random_sequence").and_then(Value::as_str) { + Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), + None => ctx.evaluate(table, random), + } + } /// `loot_table` drawing from any random (a random sequence). pub fn loot_table_from( &self, diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 0d761c7c6..791daf7c2 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -527,4 +527,28 @@ impl Behaviours { self.sim(level, ticks) .use_without_item(pos, face, hit, player) } + /// `BlockState.useItemOn` with `item` in the main hand, then, when the + /// block asks to try with an empty hand (the default), `useWithoutItem`. + /// `SweetBerryBushBlock.useItemOn` passes bone meal on a bush that can + /// still grow on to the item. + #[allow(clippy::too_many_arguments)] + pub fn use_item_on( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + face: Direction, + hit: Vec3, + player: PlayerContext, + item: Option<&str>, + ) -> InteractionResult { + let state = level.block_state(pos); + if item == Some("minecraft:bone_meal") + && self.data(state).chain.contains(&Class::SweetBerryBush) + && self.table.int(state, self.props.age) < 3 + { + return InteractionResult::Pass; + } + self.use_without_item(level, ticks, pos, face, hit, player) + } } 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 89dda66f6..721d260f4 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -295,6 +295,8 @@ public final class VanillaDispenserOracle { remove(w, origin, f.getAsJsonObject("remove")); } else if (f.has("use")) { used = use(w, origin, f.getAsJsonObject("use")); + } else if (f.has("use_item")) { + used = useItem(w, origin, f.getAsJsonObject("use_item")); } else if (f.has("hopper")) { // HopperBlockEntity.pushItemsTick, once. var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin); @@ -410,6 +412,93 @@ public final class VanillaDispenserOracle { return out; } + /** + * The player of a "use_item" case: a `User` that also has abilities, food, + * item cooldowns and a place (away from the clicked block), and records + * starting to use its item instead of syncing it. + */ + static final class Clicker extends net.minecraft.server.level.ServerPlayer { + VanillaBlockUpdateOracle.World world; + boolean creative, sneaking; + ItemStack hand; + List stats; + String using; + Clicker() { + super(null, null, null, null); + } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public boolean isSpectator() { return false; } + @Override public boolean isSecondaryUseActive() { return sneaking; } + @Override public boolean isShiftKeyDown() { return sneaking; } + @Override public boolean isDescending() { return sneaking; } + @Override public EntityType getType() { return EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; } + @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) { + return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY; + } + @Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) { + if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack; + } + @Override public void startUsingItem(net.minecraft.world.InteractionHand h) { + using = BuiltInRegistries.ITEM.getKey(getItemInHand(h).getItem()).toString(); + } + @Override public boolean isUsingItem() { return using != null; } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { + stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count); + } + } + + /** + * A right click on the top of the block at `pos` (`ServerPlayerGameMode.useItemOn` + * of the real game mode, survival or creative): the block's `useItemOn` and + * `useWithoutItem`, then the item's `useOn` (`BlockItem.place`, falling back + * to eating a consumable), and `useItem` when that passes, as + * `Minecraft.startUseItem` goes on to. The statistics, the held stack and + * the item the player started using follow. + */ + static List useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception { + Clicker player = (Clicker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Clicker.class); + player.world = w; + player.creative = use.get("creative").getAsBoolean(); + player.sneaking = use.get("sneaking").getAsBoolean(); + player.hand = stack(use.get("item").getAsString()); + player.stats = new ArrayList<>(); + var abilities = new net.minecraft.world.entity.player.Abilities(); + abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative; + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", abilities); + var food = new net.minecraft.world.food.FoodData(); + food.setFoodLevel(use.get("food").getAsInt()); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "foodData", food); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "cooldowns", new net.minecraft.world.item.ItemCooldowns()); + var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); + VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); + // Standing three blocks south of the clicked block, looking down at it. + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); + VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); + VanillaBlockUpdateOracle.set(Entity.class, player, "xRot", 90f); + var gameMode = new net.minecraft.server.level.ServerPlayerGameMode(player); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayerGameMode.class, gameMode, "gameModeForPlayer", + player.creative ? net.minecraft.world.level.GameType.CREATIVE : net.minecraft.world.level.GameType.SURVIVAL); + var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0), + net.minecraft.core.Direction.UP, pos, false); + var hand = net.minecraft.world.InteractionHand.MAIN_HAND; + var result = gameMode.useItemOn(player, w, player.getItemInHand(hand), hand, hit); + // Minecraft.startUseItem: a click on a block that neither succeeded nor + // failed goes on to use the item in the same hand. + if (!(result instanceof net.minecraft.world.InteractionResult.Success) + && !(result instanceof net.minecraft.world.InteractionResult.Fail) && !player.hand.isEmpty()) { + gameMode.useItem(player, w, player.getItemInHand(hand), hand); + } + List out = new ArrayList<>(player.stats); + out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using)); + return out; + } + /** 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()); diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py new file mode 100644 index 000000000..57080c880 --- /dev/null +++ b/tools/test_use_item_on_parity.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Compare a player's right click on a block with vanilla's, for items that are +both food and blocks (sweet and glow berries, carrots, potatoes) and for sweet +berry bushes. + +Every case has a block at the origin, something above it, and a player three +blocks south, survival or creative, hungry or full, sneaking or not, who +right-clicks the top face of the origin holding an item. Vanilla runs the real +`ServerPlayerGameMode.useItemOn` over the headless level of the dispenser +harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and +`useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` +passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its +`mayPlaceOn` rules, `BoneMealItem.useOn`, and eating a consumable that could +not be placed). Horizon runs `use_item_as_player` on that hit in a headless +game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, +level events, sounds, game events, the used statistic, the held stack, the +item the player started using, and the level random afterwards. +""" +import json +import os +import random +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 + +# Blocks the item is used on: the supports of the planted blocks and others. +GROUNDS = ['grass_block', 'dirt', 'coarse_dirt', 'podzol', 'rooted_dirt', 'moss_block', 'pale_moss_block', 'mud', + 'muddy_mangrove_roots', 'farmland', 'stone', 'sand', 'gravel', 'clay', 'snow_block', 'oak_planks'] +ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'carrot', 'potato', 'bone_meal', + 'wheat_seeds', 'beetroot_seeds', 'apple'] +# What is in the way above the clicked block. +ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern'] + + +def cases(facts, count, seed): + rng = random.Random(seed) + states = d.States(facts) + for n in range(count): + case = {**h.environment(rng), 'pos': [0, 0, 0]} + case.pop('raining', None) + case.pop('thundering', None) + cells = [] + item = rng.choice(ITEMS) + if rng.random() < 0.3: + # A sweet berry bush on grass: pick it, bone meal it, or plant against it. + age = rng.randrange(4) + cells.append([0, 0, 0, states.get('sweet_berry_bush', age=str(age))]) + cells.append([0, -1, 0, states.get(rng.choice(['grass_block', 'dirt', 'podzol', 'farmland']))]) + item = rng.choice(['bone_meal', 'bone_meal', 'sweet_berries', 'apple', '-', 'stick']) + else: + ground = rng.choice(GROUNDS) + cells.append([0, 0, 0, states.any(rng, ground) if ground == 'farmland' else states.get(ground)]) + above = rng.choice(ABOVE) + if above != 'air': + cells.append([0, 1, 0, states.get(above)]) + if item == 'glow_berries' and rng.random() < 0.5: + # A ceiling two blocks up for the cave vines to hang from. + cells.append([0, 2, 0, states.get(rng.choice(['stone', 'dirt', 'oak_leaves']))]) + if item == 'bone_meal' and ground in ('grass_block', 'moss_block', 'pale_moss_block'): + # Bone meal on spreading blocks is the bone meal harness's. + item = 'sweet_berries' + held = '-' if item == '-' else d.plain(item, rng.choice([1, 1, 2, 16, 64])) + case['use_item'] = {'item': held, 'creative': rng.random() < 0.2, 'sneaking': rng.random() < 0.2, + 'food': rng.choice([20, 20, 19, 10, 0])} + case['cells'] = cells + case['items'] = [] + case['mode'] = 'dispense' + yield case + + +def kind(case, facts): + first = facts.states[case['cells'][0][3]][0].split(':')[1] + item = case['use_item']['item'] + item = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand' + return f'{item} on {first}' + + +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'] + work = lab.LOCAL / 'use-item-on-parity' + work.mkdir(parents=True, exist_ok=True) + all_cases = list(cases(facts, 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 = {}, {} + planted = eaten = 0 + for case, a, b in zip(all_cases, native, rust): + if a and a[0].startswith('error'): + errors.setdefault(a[0], []).append(case) + continue + planted += any(line.startswith('set 0,1,0') for line in a) + eaten += any(line.startswith('held') and not line.endswith('using -') for line in a) + if not d.same(a, b): + groups.setdefault(kind(case, facts), []).append((case, a, b)) + for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])): + print(f'oracle error x{len(entries)}: {name}') + 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) + ' use=' + json.dumps(case['use_item'])) + 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); ' + f'vanilla planted in {planted} and started eating in {eaten}') + h.finish(total + skipped) + + +if __name__ == '__main__': + main()