Port the cauldron item interactions and test them against vanilla
Using a bucket, bottle, water potion, dyed armour, patterned banner or dyed shulker box on an empty, water, lava or powder snow cauldron follows CauldronInteractions, including the creative-mode stack rules of ItemUtils.createFilledResult and the underwater refusal for lava and powder snow. A harness runs every item against every cauldron state in vanilla's own useItemOn and compares the result, block writes, sounds, drops and inventory. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
//! Cauldron interactions for tools/test_cauldron_parity.py: reads one JSON
|
||||
//! case per line and prints "result TAB events TAB inventory".
|
||||
//!
|
||||
//! usage: cauldron_fixture RESOURCES INPUT OUTPUT
|
||||
use horizon_client::{
|
||||
cauldron::{Outcome, Player, interact},
|
||||
crafting::Recipes,
|
||||
item_data::{canon_stack, parse_stack},
|
||||
items::{ItemStack, Items},
|
||||
menu::{Env, Kind, Menu},
|
||||
};
|
||||
use horizon_world::chunk::BlockState;
|
||||
use serde_json::Value;
|
||||
use std::{fs, path::Path};
|
||||
|
||||
struct Stand<'a> {
|
||||
menu: Menu,
|
||||
env: &'a Env<'a>,
|
||||
events: Vec<String>,
|
||||
hand: Option<ItemStack>,
|
||||
}
|
||||
|
||||
impl Player for Stand<'_> {
|
||||
fn creative(&self) -> bool {
|
||||
self.menu.creative
|
||||
}
|
||||
fn hand(&mut self) -> &mut Option<ItemStack> {
|
||||
&mut self.hand
|
||||
}
|
||||
fn add(&mut self, stack: &mut ItemStack) -> bool {
|
||||
// The held stack lives in inventory slot 0 for Inventory.add.
|
||||
self.menu.set_player_item(0, self.hand.take());
|
||||
let added = self.menu.give(self.env, stack);
|
||||
self.hand = self.menu.player_item(0).cloned();
|
||||
self.menu.set_player_item(0, None);
|
||||
added
|
||||
}
|
||||
fn contains(&self, stack: &ItemStack) -> bool {
|
||||
self.menu.player_contains(stack)
|
||||
|| self
|
||||
.hand
|
||||
.as_ref()
|
||||
.is_some_and(|h| h.same_item_same_components(stack))
|
||||
}
|
||||
fn drop_stack(&mut self, stack: ItemStack) {
|
||||
self.events
|
||||
.push(format!("drop {}", canon_stack(Some(&stack))));
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(text: &str) -> BlockState {
|
||||
let (name, props) = text.split_once('|').unwrap_or((text, ""));
|
||||
BlockState {
|
||||
name: name.to_owned(),
|
||||
properties: props
|
||||
.split(',')
|
||||
.filter(|p| !p.is_empty())
|
||||
.filter_map(|p| p.split_once('='))
|
||||
.map(|(k, v)| (k.to_owned(), v.to_owned()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn describe(state: &BlockState) -> String {
|
||||
let props: Vec<String> = state
|
||||
.properties
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect();
|
||||
format!("{}|{}", state.name, props.join(","))
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let root = Path::new(args.get(1).ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?);
|
||||
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for line in input.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let mut menu = Menu::new(Kind::Inventory);
|
||||
menu.creative = case["creative"].as_bool().unwrap_or(false);
|
||||
for pair in case["inventory"].as_array().ok_or("inventory")? {
|
||||
menu.set_player_item(
|
||||
pair[0].as_u64().unwrap_or(0) as usize,
|
||||
parse_stack(pair[1].as_str().unwrap_or("-"))?,
|
||||
);
|
||||
}
|
||||
let held = parse_stack(case["held"].as_str().unwrap_or("-"))?;
|
||||
let mut stand = Stand {
|
||||
menu,
|
||||
env: &env,
|
||||
events: Vec::new(),
|
||||
hand: held,
|
||||
};
|
||||
let cauldron = parse(case["state"].as_str().unwrap_or_default());
|
||||
let result = interact(
|
||||
&items,
|
||||
&cauldron,
|
||||
case["under_water"].as_bool().unwrap_or(false),
|
||||
&mut stand,
|
||||
);
|
||||
if let Some(block) = &result.block {
|
||||
stand.events.push(format!("set {}", describe(block)));
|
||||
}
|
||||
if let Some(sound) = result.sound {
|
||||
stand.events.push(format!("sound {sound}"));
|
||||
}
|
||||
let kind = match result.outcome {
|
||||
Outcome::Success => "success",
|
||||
Outcome::Consume => "consume",
|
||||
Outcome::Pass => "pass",
|
||||
};
|
||||
stand.menu.set_player_item(0, stand.hand.take());
|
||||
let inventory: Vec<String> = (0..41)
|
||||
.filter_map(|i| {
|
||||
stand
|
||||
.menu
|
||||
.player_item(i)
|
||||
.map(|s| format!("{i}={}", canon_stack(Some(s))))
|
||||
})
|
||||
.collect();
|
||||
out += &format!("{kind}\t{}\t{}\n", stand.events.join(";"), inventory.join(" "));
|
||||
}
|
||||
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
//! `CauldronInteractions`: what an item does to an empty, water, lava or
|
||||
//! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item
|
||||
//! with vanilla's `useItemOn`.
|
||||
use crate::items::{ItemStack, Items};
|
||||
use horizon_world::chunk::BlockState;
|
||||
|
||||
/// The player side of an interaction.
|
||||
pub trait Player {
|
||||
fn creative(&self) -> bool;
|
||||
/// The stack in the interacting hand.
|
||||
fn hand(&mut self) -> &mut Option<ItemStack>;
|
||||
/// `Inventory.add`; the leftover stays in `stack`.
|
||||
fn add(&mut self, stack: &mut ItemStack) -> bool;
|
||||
/// `Inventory.contains`.
|
||||
fn contains(&self, stack: &ItemStack) -> bool;
|
||||
fn drop_stack(&mut self, stack: ItemStack);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Outcome {
|
||||
/// `InteractionResult.SUCCESS`
|
||||
Success,
|
||||
/// `InteractionResult.CONSUME`
|
||||
Consume,
|
||||
/// `TRY_WITH_EMPTY_HAND`
|
||||
Pass,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Interaction {
|
||||
pub outcome: Outcome,
|
||||
/// The cauldron's new state.
|
||||
pub block: Option<BlockState>,
|
||||
pub sound: Option<&'static str>,
|
||||
}
|
||||
|
||||
fn state(name: &str, level: Option<u8>) -> BlockState {
|
||||
BlockState {
|
||||
name: name.to_owned(),
|
||||
properties: level
|
||||
.map(|l| ("level".to_owned(), l.to_string()))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pass() -> Interaction {
|
||||
Interaction {
|
||||
outcome: Outcome::Pass,
|
||||
block: None,
|
||||
sound: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `ItemUtils.createFilledResult`.
|
||||
fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
|
||||
let creative = player.creative();
|
||||
if limit_creative && creative {
|
||||
if !player.contains(&new) {
|
||||
let mut new = new;
|
||||
player.add(&mut new);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let hand = player.hand();
|
||||
if !creative && let Some(held) = hand.as_mut() {
|
||||
held.count -= 1;
|
||||
if held.count == 0 {
|
||||
*hand = None;
|
||||
}
|
||||
}
|
||||
if hand.is_none() {
|
||||
*hand = Some(new);
|
||||
return;
|
||||
}
|
||||
let mut new = new;
|
||||
if !player.add(&mut new) {
|
||||
player.drop_stack(new);
|
||||
}
|
||||
}
|
||||
|
||||
/// `LayeredCauldronBlock.lowerFillLevel`.
|
||||
fn lowered(cauldron: &BlockState) -> BlockState {
|
||||
let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(1);
|
||||
if level <= 1 {
|
||||
state("minecraft:cauldron", None)
|
||||
} else {
|
||||
let mut next = cauldron.clone();
|
||||
next.properties.insert("level".into(), (level - 1).to_string());
|
||||
next
|
||||
}
|
||||
}
|
||||
|
||||
fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction {
|
||||
Interaction {
|
||||
outcome: Outcome::Success,
|
||||
block: Some(block),
|
||||
sound,
|
||||
}
|
||||
}
|
||||
|
||||
const COLORS: [&str; 16] = [
|
||||
"white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan",
|
||||
"purple", "blue", "brown", "green", "red", "black",
|
||||
];
|
||||
|
||||
/// The cauldron interaction of the held item (`useItemOn`); the hand stack is
|
||||
/// changed through `player`.
|
||||
pub fn interact(
|
||||
items: &Items,
|
||||
cauldron: &BlockState,
|
||||
under_water: bool,
|
||||
player: &mut dyn Player,
|
||||
) -> Interaction {
|
||||
let Some(held) = player.hand().clone() else {
|
||||
return pass();
|
||||
};
|
||||
let kind = match cauldron.name.as_str() {
|
||||
"minecraft:cauldron" => "empty",
|
||||
"minecraft:water_cauldron" => "water",
|
||||
"minecraft:lava_cauldron" => "lava",
|
||||
"minecraft:powder_snow_cauldron" => "powder_snow",
|
||||
_ => return pass(),
|
||||
};
|
||||
let level: u8 = cauldron.properties.get("level").and_then(|l| l.parse().ok()).unwrap_or(0);
|
||||
let item = &*held.item;
|
||||
let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water");
|
||||
// Dispatcher.get: tags first, then the item map.
|
||||
if kind == "water"
|
||||
&& items
|
||||
.item_tags
|
||||
.get("minecraft:cauldron_can_remove_dye")
|
||||
.is_some_and(|members| members.contains(item))
|
||||
{
|
||||
if held.data().and_then(|d| d.dyed_color).is_none() {
|
||||
return pass();
|
||||
}
|
||||
if let Some(stack) = player.hand().as_mut() {
|
||||
stack.data_mut().dyed_color = None;
|
||||
stack.tidy();
|
||||
}
|
||||
return changed(lowered(cauldron), None);
|
||||
}
|
||||
let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| {
|
||||
if !can_fill {
|
||||
return pass();
|
||||
}
|
||||
filled(player, ItemStack::new(new, 1), true);
|
||||
changed(state("minecraft:cauldron", None), Some(sound))
|
||||
};
|
||||
let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| {
|
||||
filled(player, ItemStack::new("minecraft:bucket", 1), true);
|
||||
changed(block, Some(sound))
|
||||
};
|
||||
match item {
|
||||
"minecraft:lava_bucket" => {
|
||||
return if under_water {
|
||||
Interaction {
|
||||
outcome: Outcome::Consume,
|
||||
block: None,
|
||||
sound: None,
|
||||
}
|
||||
} else {
|
||||
empty_bucket(
|
||||
player,
|
||||
state("minecraft:lava_cauldron", None),
|
||||
"minecraft:item.bucket.empty_lava",
|
||||
)
|
||||
};
|
||||
}
|
||||
"minecraft:water_bucket" => {
|
||||
return empty_bucket(
|
||||
player,
|
||||
state("minecraft:water_cauldron", Some(3)),
|
||||
"minecraft:item.bucket.empty",
|
||||
);
|
||||
}
|
||||
"minecraft:powder_snow_bucket" => {
|
||||
return if under_water {
|
||||
Interaction {
|
||||
outcome: Outcome::Consume,
|
||||
block: None,
|
||||
sound: None,
|
||||
}
|
||||
} else {
|
||||
empty_bucket(
|
||||
player,
|
||||
state("minecraft:powder_snow_cauldron", Some(3)),
|
||||
"minecraft:item.bucket.empty_powder_snow",
|
||||
)
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match (kind, item) {
|
||||
("empty", "minecraft:potion") => {
|
||||
if !water_potion {
|
||||
return pass();
|
||||
}
|
||||
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
|
||||
changed(
|
||||
state("minecraft:water_cauldron", Some(1)),
|
||||
Some("minecraft:item.bottle.empty"),
|
||||
)
|
||||
}
|
||||
("water", "minecraft:bucket") => fill_bucket(
|
||||
player,
|
||||
"minecraft:water_bucket",
|
||||
level == 3,
|
||||
"minecraft:item.bucket.fill",
|
||||
),
|
||||
("water", "minecraft:glass_bottle") => {
|
||||
filled(
|
||||
player,
|
||||
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"),
|
||||
true,
|
||||
);
|
||||
changed(lowered(cauldron), Some("minecraft:item.bottle.fill"))
|
||||
}
|
||||
("water", "minecraft:potion") => {
|
||||
if level == 3 || !water_potion {
|
||||
return pass();
|
||||
}
|
||||
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
|
||||
let mut next = cauldron.clone();
|
||||
// BlockState.cycle on a 1..=3 property
|
||||
next.properties
|
||||
.insert("level".into(), (level % 3 + 1).to_string());
|
||||
changed(next, Some("minecraft:item.bottle.empty"))
|
||||
}
|
||||
("water", name)
|
||||
if name
|
||||
.strip_prefix("minecraft:")
|
||||
.and_then(|n| n.strip_suffix("_banner"))
|
||||
.is_some_and(|c| COLORS.contains(&c)) =>
|
||||
{
|
||||
let layers = held.data().map_or(0, |d| d.banner_patterns.len());
|
||||
if layers == 0 {
|
||||
return pass();
|
||||
}
|
||||
let mut cleaned = held.clone();
|
||||
cleaned.count = 1;
|
||||
cleaned.data_mut().banner_patterns.pop();
|
||||
cleaned.tidy();
|
||||
filled(player, cleaned, false);
|
||||
changed(lowered(cauldron), None)
|
||||
}
|
||||
("water", name)
|
||||
if name
|
||||
.strip_prefix("minecraft:")
|
||||
.and_then(|n| n.strip_suffix("_shulker_box"))
|
||||
.is_some_and(|c| COLORS.contains(&c)) =>
|
||||
{
|
||||
filled(player, held.transmute("minecraft:shulker_box", 1), false);
|
||||
changed(lowered(cauldron), None)
|
||||
}
|
||||
("lava", "minecraft:bucket") => fill_bucket(
|
||||
player,
|
||||
"minecraft:lava_bucket",
|
||||
true,
|
||||
"minecraft:item.bucket.fill_lava",
|
||||
),
|
||||
("powder_snow", "minecraft:bucket") => fill_bucket(
|
||||
player,
|
||||
"minecraft:powder_snow_bucket",
|
||||
level == 3,
|
||||
"minecraft:item.bucket.fill_powder_snow",
|
||||
),
|
||||
_ => pass(),
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod block_transform;
|
||||
pub mod blocks;
|
||||
pub mod bossbar;
|
||||
pub mod brewing;
|
||||
pub mod cauldron;
|
||||
pub mod chat;
|
||||
pub mod chunk;
|
||||
pub mod clock;
|
||||
|
||||
@@ -278,6 +278,23 @@ impl Menu {
|
||||
self.containers[PLAYER][i].as_ref()
|
||||
}
|
||||
|
||||
pub fn set_player_item(&mut self, i: usize, stack: Option<ItemStack>) {
|
||||
self.containers[PLAYER][i] = stack;
|
||||
}
|
||||
|
||||
/// `Inventory.add`: the leftover stays in `stack`.
|
||||
pub fn give(&mut self, env: &Env, stack: &mut ItemStack) -> bool {
|
||||
self.inventory_add(env, stack)
|
||||
}
|
||||
|
||||
/// `Inventory.contains(stack)`.
|
||||
pub fn player_contains(&self, stack: &ItemStack) -> bool {
|
||||
self.containers[PLAYER]
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|have| have.same_item_same_components(stack))
|
||||
}
|
||||
|
||||
// ---- item helpers ----
|
||||
|
||||
fn max_stack(env: &Env, stack: &ItemStack) -> u32 {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.EntityEquipment;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.AbstractCauldronBlock;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.Property;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
|
||||
/**
|
||||
* Original oracle: a cauldron's useItemOn (CauldronInteractions) with a
|
||||
* recording stand-in level and player. Each case line is JSON: cauldron state
|
||||
* ("name|prop=value"), the held stack, creative, whether water is above. The
|
||||
* output line lists the result, block writes, sounds, the final inventory and
|
||||
* drops.
|
||||
*/
|
||||
public final class VanillaCauldronOracle {
|
||||
static Object unsafe;
|
||||
static java.lang.reflect.Method allocate;
|
||||
static final List<String> events = new ArrayList<>();
|
||||
static boolean underWater;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) {
|
||||
try {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static void set(Object target, Class<?> owner, String name, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
f.set(target, value);
|
||||
}
|
||||
|
||||
static String describe(BlockState state) {
|
||||
StringBuilder out = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()).append('|');
|
||||
List<Property<?>> props = new ArrayList<>(state.getProperties());
|
||||
props.sort(Comparator.comparing(Property::getName));
|
||||
boolean first = true;
|
||||
for (Property<?> p : props) {
|
||||
out.append(first ? "" : ",").append(p.getName()).append('=').append(name(state, p));
|
||||
first = false;
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static String name(BlockState state, Property p) {
|
||||
return p.getName(state.getValue(p));
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static BlockState parse(String text) {
|
||||
String[] parts = text.split("\\|", -1);
|
||||
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.parse(parts[0]));
|
||||
BlockState state = block.defaultBlockState();
|
||||
if (!parts[1].isEmpty()) {
|
||||
for (String kv : parts[1].split(",")) {
|
||||
String[] pair = kv.split("=");
|
||||
Property p = block.getStateDefinition().getProperty(pair[0]);
|
||||
state = state.setValue(p, (Comparable) p.getValue(pair[1]).orElseThrow());
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
static final class World extends ServerLevel {
|
||||
World() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
@Override public boolean isClientSide() { return false; }
|
||||
@Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int limit) { events.add("set " + describe(state)); return true; }
|
||||
@Override public FluidState getFluidState(BlockPos pos) { return underWater ? Fluids.WATER.defaultFluidState() : Fluids.EMPTY.defaultFluidState(); }
|
||||
@Override public void playSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) {
|
||||
events.add("sound " + BuiltInRegistries.SOUND_EVENT.getKey(s));
|
||||
}
|
||||
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, net.minecraft.world.phys.Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
|
||||
@Override public net.minecraft.core.RegistryAccess registryAccess() { return ParityData.access; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
|
||||
}
|
||||
|
||||
static final class FakePlayer extends ServerPlayer {
|
||||
boolean creative;
|
||||
Inventory inv;
|
||||
FakePlayer() {
|
||||
super(null, null, null, null);
|
||||
}
|
||||
@Override public Inventory getInventory() { return inv; }
|
||||
@Override public boolean hasInfiniteMaterials() { return creative; }
|
||||
@Override public boolean isCreative() { return creative; }
|
||||
@Override public void setItemInHand(InteractionHand hand, ItemStack stack) { inv.setItem(0, stack); }
|
||||
@Override public ItemStack getItemInHand(InteractionHand hand) { return inv.getItem(0); }
|
||||
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { }
|
||||
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
|
||||
if (!stack.isEmpty()) events.add("drop " + ParityData.canon(stack));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
unsafe = field.get(null);
|
||||
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (String line : (Iterable<String>) lines::iterator) {
|
||||
var f = JsonParser.parseString(line).getAsJsonObject();
|
||||
try {
|
||||
events.clear();
|
||||
underWater = f.get("under_water").getAsBoolean();
|
||||
var world = make(World.class);
|
||||
var player = make(FakePlayer.class);
|
||||
player.creative = f.get("creative").getAsBoolean();
|
||||
player.inv = new Inventory(player, new EntityEquipment());
|
||||
for (var other : f.getAsJsonArray("inventory")) {
|
||||
var pair = other.getAsJsonArray();
|
||||
player.inv.setItem(pair.get(0).getAsInt(), ParityData.stack(pair.get(1).getAsString()));
|
||||
}
|
||||
ItemStack held = ParityData.stack(f.get("held").getAsString());
|
||||
player.inv.setItem(0, held);
|
||||
BlockState state = parse(f.get("state").getAsString());
|
||||
var cauldron = (AbstractCauldronBlock) state.getBlock();
|
||||
var use = net.minecraft.world.level.block.state.BlockBehaviour.class.getDeclaredMethod("useItemOn", ItemStack.class, BlockState.class,
|
||||
net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, net.minecraft.world.phys.BlockHitResult.class);
|
||||
use.setAccessible(true);
|
||||
InteractionResult result = (InteractionResult) use.invoke(cauldron, held, state, world, BlockPos.ZERO, player, InteractionHand.MAIN_HAND, null);
|
||||
String kind = result == InteractionResult.SUCCESS ? "success" : result == InteractionResult.CONSUME ? "consume"
|
||||
: result == InteractionResult.TRY_WITH_EMPTY_HAND ? "pass" : result.toString();
|
||||
StringBuilder inventory = new StringBuilder();
|
||||
for (int i = 0; i < 41; i++) {
|
||||
ItemStack s = player.inv.getItem(i);
|
||||
if (!s.isEmpty()) inventory.append(i).append('=').append(ParityData.canon(s)).append(' ');
|
||||
}
|
||||
out.println(kind + "\t" + String.join(";", events) + "\t" + inventory.toString().trim());
|
||||
} catch (Throwable e) {
|
||||
out.println("error " + e.getClass().getSimpleName() + " " + e.getMessage());
|
||||
if (System.getenv("CAULDRON_TRACE") != null) e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare cauldron item interactions with vanilla's CauldronInteractions.
|
||||
|
||||
The Java oracle (VanillaCauldronOracle) calls the cauldron block's useItemOn
|
||||
with a recording level and player; the Rust example (cauldron_fixture) runs
|
||||
horizon_client::cauldron. Every item is used on every cauldron state (empty,
|
||||
water, lava and powder snow at each level), with water potions, dyed armour,
|
||||
patterned banners and shulker boxes, in survival and creative, under water or
|
||||
not, and with a crowded inventory. The result, block writes, sounds, drops and
|
||||
the final inventory are compared.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
try:
|
||||
from . import interaction_lab as lib, lab
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
import lab
|
||||
|
||||
STATES = ['minecraft:cauldron|', 'minecraft:water_cauldron|level=1', 'minecraft:water_cauldron|level=2',
|
||||
'minecraft:water_cauldron|level=3', 'minecraft:lava_cauldron|', 'minecraft:powder_snow_cauldron|level=1',
|
||||
'minecraft:powder_snow_cauldron|level=3']
|
||||
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
|
||||
'blue', 'brown', 'green', 'red', 'black']
|
||||
|
||||
|
||||
def snbt(item, count=1, **components):
|
||||
body = ','.join('"minecraft:%s":%s' % (k, v) for k, v in sorted(components.items()))
|
||||
return '{id:"%s",count:%d%s}' % (item, count, ',components:{%s}' % body if body else '')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=7)
|
||||
parser.add_argument('--limit', type=int, default=4)
|
||||
args = parser.parse_args()
|
||||
work = lib.work_dir('cauldron-parity')
|
||||
vanilla = lib.Vanilla(work)
|
||||
vanilla.compile('ParityData', 'VanillaCauldronOracle')
|
||||
items = json.loads((lib.RESOURCES / 'items.json').read_text())
|
||||
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
|
||||
rng = random.Random(args.seed)
|
||||
held = []
|
||||
for name, info in items.items():
|
||||
if name == 'minecraft:air':
|
||||
continue
|
||||
top = info.get('minecraft:max_stack_size', 64)
|
||||
held.append(snbt(name, 1))
|
||||
held.append(snbt(name, rng.randrange(1, top + 1)))
|
||||
for color in DYES:
|
||||
for layers in range(0, 4):
|
||||
body = '[%s]' % ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(patterns), rng.choice(DYES)) for _ in range(layers))
|
||||
held.append(snbt('minecraft:%s_banner' % color, rng.choice([1, 3]), banner_patterns=body))
|
||||
held.append(snbt('minecraft:%s_shulker_box' % color, rng.choice([1, 2])))
|
||||
for item in ['leather_helmet', 'leather_chestplate', 'leather_leggings', 'leather_boots', 'leather_horse_armor', 'wolf_armor']:
|
||||
held.append(snbt('minecraft:' + item, 1, dyed_color=rng.randrange(1 << 24)))
|
||||
for potion in ['minecraft:water', 'minecraft:healing', 'minecraft:awkward']:
|
||||
for item in ['potion', 'splash_potion', 'lingering_potion']:
|
||||
held.append(snbt('minecraft:' + item, rng.choice([1, 2]), potion_contents='{potion:"%s"}' % potion))
|
||||
cases = []
|
||||
filler = [snbt(i, 64) for i in ['minecraft:stone', 'minecraft:dirt', 'minecraft:cobblestone']]
|
||||
for state in STATES:
|
||||
for stack in held:
|
||||
crowded = rng.random() < 0.25
|
||||
inventory = [[i, rng.choice(filler)] for i in range(1, 36)] if crowded else []
|
||||
if not crowded and rng.random() < 0.3:
|
||||
inventory = [[rng.randrange(1, 36), snbt('minecraft:bucket', rng.randrange(1, 16))]]
|
||||
cases.append({'state': state, 'held': stack, 'creative': rng.random() < 0.3, 'under_water': rng.random() < 0.3,
|
||||
'inventory': inventory})
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
|
||||
vanilla.run('VanillaCauldronOracle', work / 'cases.jsonl', work / 'native.txt')
|
||||
lib.cargo_example('horizon-client', 'cauldron_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
|
||||
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
|
||||
lambda case, line: case['state'].split('|')[0] + ' ' + line.split('\t')[0],
|
||||
lambda case: json.dumps(case)[:700], args.limit)
|
||||
raise SystemExit(1 if total else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user