Port every crafting recipe type and test recipes against vanilla

The crafting module now matches shapeless recipes with a full bipartite assignment, shrinks shaped patterns like ShapedRecipePattern, keeps result components (suspicious stew effects), and implements the transmute, dye, imbue (tipped arrow), book cloning, firework rocket/star/fade, decorated pot, repair item, map extending, banner duplicate and shield decoration recipes with vanilla's matching and assembly. Crafting remainders now follow Item.craftRemainder only and are placed on the grid by recipe, so cloned books and duplicated banners stay. Stacks gain dyed colour, firework explosion, pot decorations, bundle contents, stew effects and map post-processing components, and their NBT now matches the codecs (defaults omitted, templates without count 1). A banner whose first layer was a rhombus was mistaken for the raid banner; that is fixed.

tools/test_recipe_parity.py drives vanilla's RecipeManager (new VanillaRecipeOracle) and the Rust recipe_fixture over 50k generated crafting, cooking, stonecutting and smithing cases and compares matches, results and remainders as canonical NBT; all match.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 14:04:56 +02:00
parent f1179cf141
commit 69c7fd925e
11 changed files with 2233 additions and 265 deletions
@@ -0,0 +1,91 @@
//! Recipe lookups for tools/test_recipe_parity.py: reads the oracle's
//! tab-separated commands (craft, cook, stonecut, smith) and prints one line
//! per command in the oracle's format.
//!
//! usage: recipe_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
enchant::Enchantments,
item_data::{canon_stack, parse_stack},
items::Items,
stations::StationRecipes,
};
use std::{fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let stations = StationRecipes::load(root, &items);
let enchantments = Enchantments::load(root);
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let stack = |i: usize| parse_stack(f[i]);
let text = match f[0] {
"craft" => {
let n: usize = f[1].parse()?;
let mut grid = Vec::new();
for i in 0..n * n {
grid.push(stack(2 + i)?);
}
match recipes.find(&grid, n) {
None => "none".to_owned(),
Some((id, result)) => {
let rest = recipes.remainders(id, &grid, n);
let rest: Vec<String> = rest
.iter()
.enumerate()
.filter_map(|(i, s)| {
Some(format!("{i}={}", canon_stack(Some(s.as_ref()?))))
})
.collect();
format!("{id}\t{}\t{}", canon_stack(Some(&result)), rest.join(";"))
}
}
}
"cook" => match stack(2)?.and_then(|s| {
recipes
.cook(&format!("minecraft:{}", f[1]), &s)
.map(|c| (c.id.clone(), c.result.clone(), c.experience, c.time))
}) {
None => "none".to_owned(),
Some((id, result, xp, time)) => {
format!("{id}\t{}\t{xp:?}\t{time}", canon_stack(Some(&result)))
}
},
"stonecut" => match stack(1)? {
None => String::new(),
Some(s) => stations
.stonecutter(&s)
.iter()
.map(|r| {
format!(
"{}={}",
r.id.trim_start_matches("minecraft:"),
canon_stack(Some(&r.result))
)
})
.collect::<Vec<_>>()
.join(";"),
},
"smith" => {
let (t, b, a) = (stack(1)?, stack(2)?, stack(3)?);
match stations.smithing_result(&enchantments, t.as_ref(), b.as_ref(), a.as_ref()) {
None => "none".to_owned(),
Some(r) => canon_stack(Some(&r)),
}
}
other => return Err(format!("unknown command {other}").into()),
};
out.push_str(&text);
out.push('\n');
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
File diff suppressed because it is too large Load Diff
+12 -4
View File
@@ -3185,9 +3185,17 @@ impl Game<'_> {
}
}
fn craft_result(&self) -> Option<ItemStack> {
self.craft_recipe().map(|(_, result)| result)
}
/// The recipe id and result of the crafting grid.
fn craft_recipe(&self) -> Option<(String, ItemStack)> {
let n = self.craft_size;
let grid: Vec<Option<ItemStack>> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect();
self.res.recipes.craft(&grid, n)
let scale = |id: i32| self.maps.data.get(&id).map(|m| m.scale);
self.res
.recipes
.find_with(&grid, n, &scale)
.map(|(name, result)| (name.to_owned(), result))
}
fn draw_inventory(&mut self, batch: &mut HudBatch) {
if self.draw_station(batch) {
@@ -3484,13 +3492,13 @@ impl Game<'_> {
if slot == 200 {
// ResultSlot: take the crafted stack and consume one of each ingredient.
let mut crafted = 0;
while let Some(result) = self.craft_result() {
while let Some((recipe, result)) = self.craft_recipe() {
let made = (result.item.clone(), result.count);
let cells = self.craft_size * self.craft_size;
let remainders = self.res.recipes.remainders(
&self.res.items,
&recipe,
&self.craft_grid[..cells],
&result,
self.craft_size,
);
if shift {
if self.give(result).is_some() {
@@ -125,7 +125,7 @@ impl Game<'_> {
true,
horizon_world::level::flags::UPDATE_CLIENTS,
);
let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result);
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
self.crafter_eject(key, facing, result, &recipe);
for rest in remainders.into_iter().flatten() {
self.crafter_eject(key, facing, rest, &recipe);
+279 -67
View File
@@ -44,6 +44,18 @@ pub struct StackData {
pub ominous_banner: bool,
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
pub ominous_amplifier: Option<u8>,
/// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB).
pub dyed_color: Option<i32>,
/// `minecraft:firework_explosion` (a firework star).
pub firework_explosion: Option<crate::particles::FireworkExplosion>,
/// `minecraft:pot_decorations`: back, left, right, front sherds.
pub pot_decorations: Option<Box<[Option<ItemStack>; 4]>>,
/// `minecraft:bundle_contents`.
pub bundle_contents: Vec<ItemStack>,
/// `minecraft:suspicious_stew_effects`: (effect id, duration).
pub stew_effects: Vec<(Arc<str>, i32)>,
/// `minecraft:map_post_processing`: 0 lock, 1 scale.
pub map_post_processing: Option<u8>,
}
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
@@ -243,6 +255,151 @@ fn read_text(t: &Tag) -> Option<String> {
}
}
/// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted).
fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag {
let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect());
let mut fields = vec![("shape", Tag::String(e.shape.name().into()))];
if !e.colors.is_empty() {
fields.push(("colors", colors(&e.colors)));
}
if !e.fade.is_empty() {
fields.push(("fade_colors", colors(&e.fade)));
}
if e.trail {
fields.push(("has_trail", Tag::Byte(1)));
}
if e.twinkle {
fields.push(("has_twinkle", Tag::Byte(1)));
}
Tag::compound(fields)
}
fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion {
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(),
_ => Vec::new(),
};
crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.map_or("small_ball", |s| s.strip_prefix("minecraft:").unwrap_or(s)),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
}
}
/// An `ItemStackTemplate`: `{id, count?, components?}`.
fn template_tag(stack: &ItemStack) -> Tag {
let mut entries = vec![("id", Tag::String((&*stack.item).into()))];
if stack.count != 1 {
entries.push(("count", Tag::Int(stack.count as i32)));
}
if let Some(components) = encode_components(stack) {
entries.push(("components", components));
}
Tag::compound(entries)
}
/// The pot prototype's decorations: a brick on every side.
pub fn all_bricks(sides: &[Option<ItemStack>; 4]) -> bool {
sides.iter().all(|s| {
s.as_ref()
.is_some_and(|s| &*s.item == "minecraft:brick" && s.count == 1 && s.extra.is_none())
})
}
fn template_from(tag: &Tag) -> Option<ItemStack> {
match tag {
Tag::String(id) => Some(ItemStack::new(&id.to_string_lossy(), 1)),
_ => {
let id = tag.get("id").and_then(string)?;
let (damage, extra) = decode_components(tag.get("components"));
Some(ItemStack {
item: Arc::from(id.as_str()),
count: tag.get("count").and_then(int).unwrap_or(1).max(1) as u32,
damage,
extra,
})
}
}
}
/// Sorted-key, type-annotated text of a tag (the differential harnesses
/// print the same form from the vanilla side).
pub fn canon_tag(tag: &Tag) -> String {
fn list(out: &mut String, prefix: &str, items: impl Iterator<Item = String>) {
out.push_str(prefix);
out.push_str(&items.collect::<Vec<_>>().join(","));
out.push(']');
}
fn go(tag: &Tag, out: &mut String) {
use std::fmt::Write as _;
match tag {
Tag::End => {}
Tag::Byte(v) => write!(out, "{v}b").unwrap(),
Tag::Short(v) => write!(out, "{v}s").unwrap(),
Tag::Int(v) => write!(out, "{v}").unwrap(),
Tag::Long(v) => write!(out, "{v}L").unwrap(),
Tag::Float(v) => write!(out, "{}f", f32::from_bits(*v)).unwrap(),
Tag::Double(v) => write!(out, "{}d", f64::from_bits(*v)).unwrap(),
Tag::String(s) => write!(
out,
"\"{}\"",
s.to_string_lossy()
.replace('\\', "\\\\")
.replace('"', "\\\"")
)
.unwrap(),
Tag::ByteArray(v) => list(out, "[B;", v.iter().map(|b| (*b as i8).to_string())),
Tag::IntArray(v) => list(out, "[I;", v.iter().map(i32::to_string)),
Tag::LongArray(v) => list(out, "[L;", v.iter().map(i64::to_string)),
Tag::List(items) => {
out.push('[');
for (i, t) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
go(t, out);
}
out.push(']');
}
Tag::Compound(map) => {
let mut keys: Vec<(String, &Tag)> =
map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
out.push('{');
for (i, (k, v)) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&k);
out.push(':');
go(v, out);
}
out.push('}');
}
}
}
let mut out = String::new();
go(tag, &mut out);
out
}
/// `canon_tag` of a stack as `ItemStack.CODEC` writes it; "-" for none.
pub fn canon_stack(stack: Option<&ItemStack>) -> String {
stack.map_or_else(
|| "-".to_owned(),
|s| canon_tag(&crate::save::item_to_nbt(s)),
)
}
/// The stack of an SNBT `ItemStack.CODEC` compound; None for "-".
pub fn parse_stack(snbt: &str) -> Result<Option<ItemStack>, String> {
if snbt == "-" {
return Ok(None);
}
let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?;
Ok(crate::save::item_from_nbt(&tag))
}
/// The `components` compound for a stack, or None when every component is default.
pub fn encode_components(stack: &ItemStack) -> Option<Tag> {
components_tag(stack.damage, stack.data())
@@ -317,40 +474,73 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.collect();
entries.push((
"minecraft:written_book_content",
Tag::compound([
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("generation", Tag::Int(i32::from(w.generation))),
("pages", Tag::List(pages)),
("resolved", Tag::Byte(1)),
]),
Tag::compound({
let mut fields = vec![
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("pages", Tag::List(pages)),
];
if w.generation != 0 {
fields.push(("generation", Tag::Int(i32::from(w.generation))));
}
fields
}),
));
}
if let Some((flight, explosions)) = &d.fireworks {
let list = explosions
.iter()
.map(|e| {
Tag::compound([
("shape", Tag::String(e.shape.name().into())),
(
"colors",
Tag::IntArray(e.colors.iter().map(|c| *c as i32).collect()),
),
(
"fade_colors",
Tag::IntArray(e.fade.iter().map(|c| *c as i32).collect()),
),
("has_trail", Tag::Byte(i8::from(e.trail))),
("has_twinkle", Tag::Byte(i8::from(e.twinkle))),
])
})
.collect();
let mut fields = Vec::new();
if *flight != 0 {
fields.push(("flight_duration", Tag::Byte(*flight as i8)));
}
if !explosions.is_empty() {
fields.push((
"explosions",
Tag::List(explosions.iter().map(explosion_tag).collect()),
));
}
entries.push(("minecraft:fireworks", Tag::compound(fields)));
}
if let Some(e) = &d.firework_explosion {
entries.push(("minecraft:firework_explosion", explosion_tag(e)));
}
if let Some(color) = d.dyed_color {
entries.push(("minecraft:dyed_color", Tag::Int(color)));
}
if let Some(sides) = &d.pot_decorations {
let mut sherds = Vec::new();
for (name, side) in ["back", "left", "right", "front"].iter().zip(sides.iter()) {
if let Some(stack) = side {
sherds.push((*name, template_tag(stack)));
}
}
entries.push(("minecraft:pot_decorations", Tag::compound(sherds)));
}
if !d.bundle_contents.is_empty() {
entries.push((
"minecraft:fireworks",
Tag::compound([
("flight_duration", Tag::Byte(*flight as i8)),
("explosions", Tag::List(list)),
]),
"minecraft:bundle_contents",
Tag::List(d.bundle_contents.iter().map(template_tag).collect()),
));
}
if !d.stew_effects.is_empty() {
entries.push((
"minecraft:suspicious_stew_effects",
Tag::List(
d.stew_effects
.iter()
.map(|(id, duration)| {
Tag::compound([
("id", Tag::String((&**id).into())),
("duration", Tag::Int(*duration)),
])
})
.collect(),
),
));
}
if let Some(mode) = d.map_post_processing {
entries.push((
"minecraft:map_post_processing",
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
));
}
if !d.charged.is_empty() {
@@ -399,7 +589,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.map(|(slot, stack)| {
Tag::compound([
("slot", Tag::Int(i32::from(*slot))),
("item", crate::save::item_to_nbt(stack)),
("item", template_tag(stack)),
])
})
.collect();
@@ -456,36 +646,54 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
_ => Vec::new(),
},
}),
fireworks: c.get("minecraft:fireworks").map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
_ => Vec::new(),
};
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list
.iter()
.map(|e| crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.unwrap_or("small_ball"),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
})
.collect(),
_ => Vec::new(),
};
(flight, explosions)
}),
fireworks: c
.get("minecraft:fireworks")
.map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list.iter().map(explosion_from).collect(),
_ => Vec::new(),
};
(flight, explosions)
})
.filter(|(flight, explosions)| !(*flight == 1 && explosions.is_empty())),
firework_explosion: c.get("minecraft:firework_explosion").map(explosion_from),
dyed_color: c
.get("minecraft:dyed_color")
.and_then(int)
.map(|v| v as i32),
pot_decorations: c
.get("minecraft:pot_decorations")
.map(|p| {
let side = |name: &str| p.get(name).and_then(template_from);
Box::new([side("back"), side("left"), side("right"), side("front")])
})
.filter(|sides| !all_bricks(sides)),
bundle_contents: match c.get("minecraft:bundle_contents") {
Some(Tag::List(list)) => list.iter().filter_map(template_from).collect(),
_ => Vec::new(),
},
stew_effects: match c.get("minecraft:suspicious_stew_effects") {
Some(Tag::List(list)) => list
.iter()
.filter_map(|e| {
Some((
Arc::from(e.get("id").and_then(string)?.as_str()),
e.get("duration").and_then(int).unwrap_or(160) as i32,
))
})
.collect(),
_ => Vec::new(),
},
map_post_processing: match c.get("minecraft:map_post_processing") {
Some(Tag::String(s)) => Some(u8::from(s.to_string_lossy() != "lock")),
Some(t) => int(t).map(|v| v.clamp(0, 1) as u8),
None => None,
},
charged: match c.get("minecraft:charged_projectiles") {
Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(),
_ => Vec::new(),
@@ -496,17 +704,21 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
.filter_map(|e| {
Some((
e.get("slot").and_then(int)?.clamp(0, 255) as u8,
crate::save::item_from_nbt(e.get("item")?)?,
template_from(e.get("item")?)?,
))
})
.collect(),
_ => Vec::new(),
},
ominous_banner: matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
),
ominous_banner: c
.get("minecraft:item_name")
.and_then(|n| n.get("translate"))
.and_then(string)
.as_deref()
== Some("block.minecraft.ominous_banner")
&& matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.len() == OMINOUS_LAYERS.len()),
ominous_amplifier: c
.get("minecraft:ominous_bottle_amplifier")
.and_then(int)
+28 -2
View File
@@ -60,7 +60,20 @@ pub struct ItemInfo {
pub equip_sound: Option<String>,
/// `jukebox_playable`: the jukebox song it plays.
pub jukebox_song: Option<String>,
/// `crafting_remainder`: what stays in the grid when the item is used in a recipe.
pub crafting_remainder: Option<String>,
/// `dye`: the dye colour name (dyes, and anything else with the component).
pub dye: Option<String>,
}
/// `Item.Properties.craftRemainder` (not a data component, so not in the
/// default-component report): what an item leaves in the grid when crafted with.
pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [
("minecraft:water_bucket", "minecraft:bucket"),
("minecraft:lava_bucket", "minecraft:bucket"),
("minecraft:milk_bucket", "minecraft:bucket"),
("minecraft:dragon_breath", "minecraft:glass_bottle"),
("minecraft:honey_bottle", "minecraft:glass_bottle"),
];
/// A reduction of `blocks_attacks.damage_reductions`.
#[derive(Clone, Debug)]
pub struct BlockReduction {
@@ -264,8 +277,6 @@ fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<S
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
let default = registry.default_state(&s.name);
@@ -275,6 +286,16 @@ impl Items {
.or_insert(BlockStateId(i as u32));
}
}
Self::load_with(root, &block_for_item)
}
/// Every item's default components and the tags, without the block <->
/// item mapping (for headless tools that never place blocks).
pub fn catalog(root: &Path) -> Result<Self> {
Self::load_with(root, &HashMap::new())
}
fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let entity_tags = load_tags(root, "entity_type")?;
let mut items = HashMap::new();
let mut order = Vec::new();
@@ -352,6 +373,11 @@ impl Items {
.as_str()
.map(str::to_owned),
jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned),
dye: c["minecraft:dye"].as_str().map(str::to_owned),
crafting_remainder: CRAFT_REMAINDERS
.iter()
.find(|(item, _)| *item == name)
.map(|(_, rest)| (*rest).to_owned()),
use_speed: c["minecraft:use_effects"]["speed_multiplier"]
.as_f64()
.unwrap_or(0.2) as f32,
+1 -1
View File
@@ -287,7 +287,7 @@ impl Book {
category: crafting_category(&category),
group: group(&grp),
display,
result: result.clone(),
result: result.create(),
});
}
for c in &recipes.cooking {
@@ -0,0 +1,132 @@
package dev.horizonlab.parity;
import java.lang.reflect.Field;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.*;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.RegistryOps;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
/**
* Shared set-up for the interaction/inventory parity oracles: the vanilla data
* pack loaded into registries (as the server does), an NBT registry ops, a
* stand-in ServerLevel that only answers registryAccess, and canonical text
* for item stacks and NBT so both sides print comparable lines.
*/
public final class ParityData {
public static HolderLookup.Provider lookup;
public static RegistryAccess access;
public static RegistryOps<Tag> ops;
public static ServerLevel level;
public static void init() throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
access = loaded.layers().compositeAccess();
ops = RegistryOps.create(NbtOps.INSTANCE, lookup);
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object unsafe = unsafeField.get(null);
level = (ServerLevel) unsafe.getClass().getMethod("allocateInstance", Class.class).invoke(unsafe, ServerLevel.class);
Field registryAccess = Level.class.getDeclaredField("registryAccess");
registryAccess.setAccessible(true);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, registryAccess);
unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, level, offset, access);
}
/** "-" is the empty stack; otherwise ItemStack.CODEC over SNBT. */
public static ItemStack stack(String snbt) throws Exception {
if (snbt.equals("-")) return ItemStack.EMPTY;
Tag tag = TagParser.parseCompoundFully(snbt);
return ItemStack.CODEC.parse(ops, tag).getOrThrow();
}
public static String canon(ItemStack stack) {
if (stack == null || stack.isEmpty()) return "-";
Tag tag = ItemStack.CODEC.encodeStart(ops, stack).getOrThrow();
return canon(tag);
}
/** Sorted-key, type-annotated text of an NBT tag. */
public static String canon(Tag tag) {
StringBuilder out = new StringBuilder();
canon(tag, out);
return out.toString();
}
private static void canon(Tag tag, StringBuilder out) {
switch (tag) {
case ByteTag t -> out.append(t.value()).append('b');
case ShortTag t -> out.append(t.value()).append('s');
case IntTag t -> out.append(t.value());
case LongTag t -> out.append(t.value()).append('L');
case FloatTag t -> out.append(t.value()).append('f');
case DoubleTag t -> out.append(t.value()).append('d');
case StringTag t -> out.append('"').append(t.value().replace("\\", "\\\\").replace("\"", "\\\"")).append('"');
case ByteArrayTag t -> {
out.append("[B;");
byte[] a = t.getAsByteArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case IntArrayTag t -> {
out.append("[I;");
int[] a = t.getAsIntArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case LongArrayTag t -> {
out.append("[L;");
long[] a = t.getAsLongArray();
for (int i = 0; i < a.length; i++) out.append(i > 0 ? "," : "").append(a[i]);
out.append(']');
}
case ListTag t -> {
out.append('[');
for (int i = 0; i < t.size(); i++) {
if (i > 0) out.append(',');
canon(t.get(i), out);
}
out.append(']');
}
case CompoundTag t -> {
out.append('{');
boolean first = true;
for (String key : new TreeSet<>(t.keySet())) {
if (!first) out.append(',');
first = false;
out.append(key).append(':');
canon(t.get(key), out);
}
out.append('}');
}
default -> throw new IllegalStateException(tag.toString());
}
}
}
@@ -0,0 +1,140 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*;
/**
* Original oracle: vanilla's RecipeManager over the data pack's recipes.
* Tab-separated commands (stacks are SNBT of ItemStack.CODEC, "-" is empty):
* craft N cells..., cook TYPE stack, stonecut stack, smith template base addition.
* "dump" prints every crafting recipe's ingredient item lists for the generator.
*/
public final class VanillaRecipeOracle {
static RecipeManager recipes;
public static void main(String[] args) throws Exception {
ParityData.init();
recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
if (args[0].equals("dump")) {
dump(Path.of(args[1]));
return;
}
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
String result;
try {
result = run(line.split("\t", -1));
} catch (Exception e) {
result = "error";
}
out.println(result);
}
}
}
static String run(String[] f) throws Exception {
switch (f[0]) {
case "craft": {
int n = Integer.parseInt(f[1]);
List<ItemStack> items = new ArrayList<>();
for (int i = 0; i < n * n; i++) items.add(ParityData.stack(f[2 + i]));
var positioned = CraftingInput.ofPositioned(n, n, items);
var input = positioned.input();
if (input.isEmpty()) return "none";
var found = recipes.getRecipeFor(RecipeType.CRAFTING, input, null);
if (found.isEmpty()) return "none";
var recipe = found.get().value();
var result = recipe.assemble(input);
var rest = recipe.getRemainingItems(input);
StringJoiner joiner = new StringJoiner(";");
for (int i = 0; i < rest.size(); i++) {
if (rest.get(i).isEmpty()) continue;
int at = (positioned.top() + i / input.width()) * n + positioned.left() + i % input.width();
joiner.add(at + "=" + ParityData.canon(rest.get(i)));
}
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(result) + "\t" + joiner;
}
case "cook": {
RecipeType<? extends AbstractCookingRecipe> type = switch (f[1]) {
case "smelting" -> RecipeType.SMELTING;
case "blasting" -> RecipeType.BLASTING;
case "smoking" -> RecipeType.SMOKING;
default -> RecipeType.CAMPFIRE_COOKING;
};
return cook(type, ParityData.stack(f[2]));
}
case "stonecut": {
var stack = ParityData.stack(f[1]);
StringJoiner joiner = new StringJoiner(";");
for (var entry : recipes.getSynchronizedStonecutterRecipes().selectByInput(stack).entries()) {
var holder = entry.recipe().recipe().get();
joiner.add(holder.id().identifier().getPath() + "=" + ParityData.canon(holder.value().assemble(new SingleRecipeInput(stack))));
}
return joiner.toString();
}
case "smith": {
var input = new SmithingRecipeInput(ParityData.stack(f[1]), ParityData.stack(f[2]), ParityData.stack(f[3]));
var found = recipes.getRecipeFor(RecipeType.SMITHING, input, null);
if (found.isEmpty()) return "none";
return ParityData.canon(found.get().value().assemble(input));
}
default:
throw new IllegalArgumentException(f[0]);
}
}
static <T extends AbstractCookingRecipe> String cook(RecipeType<T> type, ItemStack stack) {
if (stack.isEmpty()) return "none";
var input = new SingleRecipeInput(stack);
var found = recipes.getRecipeFor(type, input, null);
if (found.isEmpty()) return "none";
var recipe = found.get().value();
return found.get().id().identifier().getPath() + "\t" + ParityData.canon(recipe.assemble(input)) + "\t" + recipe.experience() + "\t" + recipe.cookingTime();
}
static String items(Ingredient ingredient) {
if (ingredient == null) return "[]";
StringBuilder row = new StringBuilder("[");
var items = ingredient.items().toList();
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
return row.append(']').toString();
}
static void dump(Path path) throws Exception {
try (var out = new PrintWriter(Files.newBufferedWriter(path, StandardCharsets.UTF_8))) {
for (var holder : recipes.getRecipes()) {
var recipe = holder.value();
if (recipe instanceof SmithingRecipe smithing) {
out.println("{\"id\":\"" + holder.id().identifier().getPath() + "\",\"kind\":\"" + recipe.getClass().getSimpleName()
+ "\",\"template\":" + items(smithing.templateIngredient().orElse(null)) + ",\"base\":" + items(smithing.baseIngredient())
+ ",\"addition\":" + items(smithing.additionIngredient().orElse(null)) + "}");
continue;
}
if (recipe.getType() != RecipeType.CRAFTING) continue;
var info = recipe.placementInfo();
StringBuilder row = new StringBuilder();
row.append("{\"id\":\"").append(holder.id().identifier().getPath()).append("\",\"kind\":\"").append(recipe.getClass().getSimpleName()).append("\",\"slots\":[");
for (int i = 0; i < info.slotsToIngredientIndex().size(); i++) row.append(i > 0 ? "," : "").append(info.slotsToIngredientIndex().getInt(i));
row.append("],\"ingredients\":[");
boolean firstIngredient = true;
for (var ingredient : info.ingredients()) {
row.append(firstIngredient ? "" : ",").append('[');
firstIngredient = false;
var items = ingredient.items().toList();
for (int i = 0; i < items.size(); i++) row.append(i > 0 ? "," : "").append('"').append(BuiltInRegistries.ITEM.getKey(items.get(i).value())).append('"');
row.append(']');
}
row.append("]}");
out.println(row);
}
}
}
}
+71
View File
@@ -0,0 +1,71 @@
"""Shared plumbing for the interaction/inventory differential harnesses
(test_recipe_parity, test_menu_click_parity, test_block_interaction_parity):
compile and run a vanilla Java oracle headlessly, run the matching Rust
example, and report differing lines grouped by a key."""
import json
import os
from pathlib import Path
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
def work_dir(name):
path = lab.LOCAL / name
path.mkdir(parents=True, exist_ok=True)
return path
class Vanilla:
"""Compiles oracles against the pinned server jar and runs them."""
def __init__(self, work):
self.lock, self.jars, self.libraries = base.verify_artifacts()
self.work = work
self.classes = work / 'classes'
self.classes.mkdir(exist_ok=True)
self.deps = os.pathsep.join(map(str, [self.jars['server'], *self.libraries]))
def compile(self, *oracles):
sources = [PARITY / (name + '.java') for name in oracles]
subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none',
'-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn',
'-cp', self.deps, '-d', str(self.classes), *map(str, sources)], check=True)
def run(self, oracle, *args, heap='2G'):
subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps,
'dev.horizonlab.parity.' + oracle, *map(str, args)], check=True)
def cargo_example(package, example, *args, profile=None):
command = ['cargo', 'run', '-q', '-j3']
if profile:
command += ['--profile', profile]
command += ['-p', package, '--example', example, '--', *map(str, args)]
subprocess.run(command, check=True, cwd=lab.ROOT)
def compare(cases, native_path, rust_path, key, describe=None, limit=3):
"""Print differing cases grouped by key(case, native_line); returns the count."""
native = Path(native_path).read_text().split('\n')
rust = Path(rust_path).read_text().split('\n')
if len(native) != len(rust):
print(f'line counts differ: native {len(native)} rust {len(rust)}')
groups = {}
for case, a, b in zip(cases, native, rust):
if a != b:
groups.setdefault(key(case, a), []).append((case, a, b))
describe = describe or (lambda case: case if isinstance(case, str) else json.dumps(case))
total = sum(len(v) for v in groups.values())
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
print(f'{name}: {len(entries)} differing')
for case, a, b in entries[:limit]:
print(f' case {describe(case)}\n native {a}\n rust {b}')
print(f'{len(cases) - total}/{len(cases)} cases match')
return total
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""Compare crafting, cooking, stonecutting and smithing with vanilla's RecipeManager.
The Java oracle (VanillaRecipeOracle) loads the data pack's recipe registry and
answers craft/cook/stonecut/smith commands; the Rust example (recipe_fixture)
answers the same commands from horizon_client::crafting and ::stations.
Crafting cases are built from every recipe's own ingredients (placed at random
offsets, mirrored, perturbed) plus focused generators for the special recipes
(banners, books, fireworks, dyeing, repair, pots, tipped arrows, maps) and
random grids. Results are compared as canonical ItemStack NBT, with the
matched recipe id and the crafting remainders.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
POTIONS = ['minecraft:healing', 'minecraft:swiftness', 'minecraft:water', 'minecraft:night_vision']
SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst']
def quote(text):
return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'
def stack(item, count=1, **components):
"""SNBT of an ItemStack.CODEC compound; component values are SNBT text."""
body = ','.join(f'{quote("minecraft:" + key)}:{value}' for key, value in sorted(components.items()))
comp = f',components:{{{body}}}' if body else ''
return f'{{id:{quote(item)},count:{count}{comp}}}'
def colors(rng, n=None):
n = rng.randrange(0, 4) if n is None else n
return '[I;' + ','.join(str(rng.randrange(1 << 24)) for _ in range(n)) + ']'
def explosion(rng):
return ('{shape:%s,colors:%s,fade_colors:%s,has_trail:%db,has_twinkle:%db}'
% (quote(rng.choice(SHAPES)), colors(rng), colors(rng), rng.randrange(2), rng.randrange(2)))
class Gen:
def __init__(self, rng, items, recipes, patterns):
self.rng = rng
self.items = items
self.recipes = recipes
self.patterns = patterns
self.durable = [k for k, v in items.items() if v.get('minecraft:max_damage')]
def layers(self, n=None):
n = self.rng.choice([0, 0, 1, 2, 6, 7]) if n is None else n
return '[' + ','.join('{pattern:%s,color:%s}' % (quote(self.rng.choice(self.patterns)), quote(self.rng.choice(DYES))) for _ in range(n)) + ']'
def book(self, generation=None):
g = self.rng.randrange(4) if generation is None else generation
return stack('minecraft:written_book', written_book_content='{title:{raw:"T"},author:"A",generation:%d,pages:[{raw:"p1"},{raw:"p2"}]}' % g)
def stack(self, item, count=None, rich=0.5):
"""A stack of the item, with the components that apply to it."""
rng = self.rng
info = self.items.get(item, {})
count = rng.choice([1, 1, 1, 2, 3]) if count is None else count
c = {}
if rng.random() < rich:
if info.get('minecraft:max_damage') and rng.random() < 0.7:
c['damage'] = str(rng.randrange(0, info['minecraft:max_damage'] + 1))
if info.get('minecraft:max_damage') and rng.random() < 0.3:
c['enchantments'] = '{%s:1}' % quote(rng.choice(['minecraft:binding_curse', 'minecraft:vanishing_curse', 'minecraft:mending', 'minecraft:unbreaking']))
if item.endswith('_banner'):
c['banner_patterns'] = self.layers()
if item == 'minecraft:shield':
if rng.random() < 0.3:
c['banner_patterns'] = self.layers(rng.randrange(1, 3))
c['base_color'] = quote(rng.choice(DYES))
if item == 'minecraft:written_book':
return self.book()
if item == 'minecraft:firework_star':
c['firework_explosion'] = explosion(rng)
if item == 'minecraft:firework_rocket':
c['fireworks'] = '{flight_duration:%db,explosions:[%s]}' % (rng.randrange(1, 4), explosion(rng))
if item in ('minecraft:lingering_potion', 'minecraft:potion', 'minecraft:splash_potion'):
c['potion_contents'] = '{potion:%s}' % quote(rng.choice(POTIONS))
if item.startswith('minecraft:leather_') or item in ('minecraft:wolf_armor',):
if rng.random() < 0.6:
c['dyed_color'] = str(rng.randrange(1 << 24))
if item.endswith('shulker_box'):
c['container'] = '[{slot:0,item:{id:"minecraft:stone",count:%d}}]' % rng.randrange(1, 64)
if item.endswith('_bundle') or item == 'minecraft:bundle':
c['bundle_contents'] = '[{id:"minecraft:stone",count:%d}]' % rng.randrange(1, 64)
if item == 'minecraft:filled_map':
c['map_id'] = str(rng.randrange(1, 5))
return stack(item, count, **c)
def plain(self, item):
return self.stack(item, rich=0.3)
def place(rng, cells, size):
"""Cells (stack list) at random free positions of a size x size grid."""
grid = ['-'] * (size * size)
spots = rng.sample(range(size * size), len(cells))
for spot, cell in zip(spots, cells):
grid[spot] = cell
return grid
def place_box(rng, width, height, cells, size):
"""A width x height pattern at a random offset of the grid."""
x0 = rng.randrange(size - width + 1)
y0 = rng.randrange(size - height + 1)
grid = ['-'] * (size * size)
for i, cell in enumerate(cells):
grid[(y0 + i // width) * size + x0 + i % width] = cell
return grid
def craft_case(grid, size):
return 'craft\t%d\t%s' % (size, '\t'.join(grid))
def recipe_cases(g, count_per):
rng = g.rng
for recipe in g.recipes:
if 'slots' not in recipe or not recipe['ingredients']:
continue
ingredients = recipe['ingredients']
slots = recipe['slots']
shaped = recipe['kind'] == 'ShapedRecipe'
if shaped:
width = recipe['width']
height = len(slots) // width
for variant in range(count_per):
pick = [g.plain(rng.choice(i)) if i else '-' for i in ingredients]
if shaped:
cells = ['-' if s < 0 else pick[s] for s in slots]
if variant % 3 == 1: # mirrored
cells = [cells[y * width + width - 1 - x] for y in range(height) for x in range(width)]
size = rng.choice([s for s in (2, 3) if s >= max(width, height)])
grid = place_box(rng, width, height, cells, size)
else:
size = 3 if len(pick) > 4 else rng.choice([2, 3])
grid = place(rng, pick, size)
yield craft_case(grid, size)
# Perturbations: drop one, swap one for a stranger, add one, shift a count.
if variant < 2:
filled = [i for i, c in enumerate(grid) if c != '-']
broken = list(grid)
broken[rng.choice(filled)] = '-'
yield craft_case(broken, size)
broken = list(grid)
broken[rng.choice(filled)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
yield craft_case(broken, size)
free = [i for i, c in enumerate(grid) if c == '-']
if free:
broken = list(grid)
broken[rng.choice(free)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
yield craft_case(broken, size)
def special_cases(g, n):
rng = g.rng
items = g.items
banners = [f'minecraft:{d}_banner' for d in DYES]
dyes = [f'minecraft:{d}_dye' for d in DYES]
armor = [k for k in items if k.startswith('minecraft:leather_') and k.count('_') == 2] + ['minecraft:wolf_armor']
boxes = [k for k in items if k.endswith('shulker_box')]
bundles = [k for k in items if k.endswith('bundle')]
skulls = [k for k in items if k.endswith('_head') or k.endswith('_skull')]
for _ in range(n):
size = rng.choice([2, 3])
# banner duplicate / shield decoration
a, b = rng.choice(banners), rng.choice(banners)
yield craft_case(place(rng, [g.stack(a, 1, 1.0), g.stack(b if rng.random() < 0.3 else a, 1, 0.5)], size), size)
yield craft_case(place(rng, [g.stack(rng.choice(banners), 1, 1.0), g.stack('minecraft:shield', 1, 0.5)], size), size)
# book cloning
books = [g.book(rng.choice([0, 0, 1, 2, 3]))] + [stack('minecraft:writable_book') for _ in range(rng.randrange(0, 4))]
if rng.random() < 0.2:
books.append(g.book())
yield craft_case(place(rng, books, 3), 3)
# fireworks
star = [stack(rng.choice(['minecraft:gunpowder'] + dyes[:2] + ['minecraft:gold_nugget', 'minecraft:feather', 'minecraft:fire_charge',
'minecraft:diamond', 'minecraft:glowstone_dust', rng.choice(skulls)]))
for _ in range(rng.randrange(1, 7))]
star += [stack('minecraft:gunpowder'), stack(rng.choice(dyes))]
yield craft_case(place(rng, star[:9], 3), 3)
fade = [g.stack('minecraft:firework_star', 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
yield craft_case(place(rng, fade, 3), 3)
rocket = [stack('minecraft:paper')] + [stack('minecraft:gunpowder') for _ in range(rng.randrange(0, 5))] + \
[g.stack('minecraft:firework_star', 1, 1.0) for _ in range(rng.randrange(0, 4))]
yield craft_case(place(rng, rocket[:9], 3), 3)
# armour dyeing, with leftovers
dye_cells = [g.stack(rng.choice(armor), 1, 0.7)] + [stack(rng.choice(dyes + ['minecraft:stick'] if rng.random() < 0.1 else dyes)) for _ in range(rng.randrange(1, 5))]
yield craft_case(place(rng, dye_cells[:9], 3), 3)
# repair
tool = rng.choice(g.durable)
pair = [g.stack(tool, 1, 1.0), g.stack(tool if rng.random() < 0.85 else rng.choice(g.durable), 1, 1.0)]
yield craft_case(place(rng, pair, size), size)
# shulker boxes and bundles
yield craft_case(place(rng, [g.stack(rng.choice(boxes + bundles), 1, 1.0), stack(rng.choice(dyes))], size), size)
multi = [g.stack(rng.choice(boxes + bundles), 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
yield craft_case(place(rng, multi, 3), 3)
# decorated pots
sherds = ['minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:archer_pottery_sherd', 'minecraft:stick', 'minecraft:blade_pottery_sherd']
pot = ['-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-']
if rng.random() < 0.2:
pot[rng.choice([0, 2, 6, 8, 4])] = stack('minecraft:brick')
yield craft_case(pot, 3)
yield craft_case([stack('minecraft:brick') if i in (1, 3, 5, 7) else '-' for i in range(9)], 3)
# tipped arrows
ring = [stack('minecraft:arrow', rng.choice([1, 2]))] * 9
ring[4] = g.stack('minecraft:lingering_potion', 1, 1.0 if rng.random() < 0.8 else 0.0)
yield craft_case(ring, 3)
# map cloning
maps = [g.stack('minecraft:filled_map', 1, 1.0)] + [stack('minecraft:map') for _ in range(rng.randrange(1, 9))]
yield craft_case(place(rng, maps, 3), 3)
# mixed junk of the interesting items
pool = banners + dyes + armor + boxes + bundles + ['minecraft:written_book', 'minecraft:writable_book', 'minecraft:firework_star',
'minecraft:paper', 'minecraft:gunpowder', 'minecraft:shield', 'minecraft:glass_bottle',
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:bowl', 'minecraft:stick']
junk = [g.stack(rng.choice(pool), None, 0.7) for _ in range(rng.randrange(1, 6))]
yield craft_case(place(rng, junk, 3), 3)
def smithing_cases(g):
rng = g.rng
for recipe in g.recipes:
if recipe['kind'].startswith('Smithing'):
for _ in range(24):
pick = lambda key: g.plain(rng.choice(recipe[key])) if recipe[key] else '-'
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), pick('addition'))
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])))
# Armour with a trim already on it.
trims = ['{material:"minecraft:iron",pattern:"minecraft:coast"}', '{material:"minecraft:gold",pattern:"minecraft:sentry"}']
for recipe in g.recipes:
if recipe['kind'] == 'SmithingTrimRecipe':
for trim in trims:
base = rng.choice(recipe['base'])
yield 'smith\t%s\t%s\t%s' % (stack(rng.choice(recipe['template'])), stack(base, 1, trim=trim), stack(rng.choice(recipe['addition'])))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--variants', type=int, default=6)
parser.add_argument('--specials', type=int, default=1500)
parser.add_argument('--random', type=int, default=4000)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
work = lib.work_dir('recipe-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaRecipeOracle')
vanilla.run('VanillaRecipeOracle', 'dump', work / 'recipes.jsonl')
recipes = [json.loads(line) for line in (work / 'recipes.jsonl').read_text().splitlines()]
# Shaped recipes: widths come from the data pack.
for recipe in recipes:
path = lib.RESOURCES / 'data/minecraft/recipe' / (recipe['id'] + '.json')
data = json.loads(path.read_text())
if recipe['kind'] == 'ShapedRecipe':
rows = [row.rstrip() for row in data['pattern']]
left = min(len(row) - len(row.lstrip()) for row in rows if row)
recipe['width'] = max(len(row) for row in rows) - left
items = json.loads((lib.RESOURCES / 'items.json').read_text())
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
rng = random.Random(args.seed)
g = Gen(rng, items, recipes, patterns)
cases = list(recipe_cases(g, args.variants))
cases += list(special_cases(g, args.specials))
pool = [k for k in items if not k.endswith('_spawn_egg') and k != 'minecraft:air']
interesting = [f'minecraft:{d}_dye' for d in DYES] + ['minecraft:paper', 'minecraft:gunpowder', 'minecraft:bowl', 'minecraft:stick',
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:water_bucket']
for _ in range(args.random):
size = rng.choice([2, 3])
cells = [g.stack(rng.choice(interesting if rng.random() < 0.6 else pool), None, 0.5) for _ in range(rng.randrange(1, size * size + 1))]
cases.append(craft_case(place(rng, cells, size), size))
for kind in ['smelting', 'blasting', 'smoking', 'campfire_cooking']:
for item in [i for i in items if i != 'minecraft:air']:
cases.append('cook\t%s\t%s' % (kind, stack(item)))
for item in [i for i in items if i != 'minecraft:air']:
cases.append('stonecut\t' + stack(item))
cases += list(smithing_cases(g))
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
vanilla.run('VanillaRecipeOracle', work / 'cases.txt', work / 'native.txt')
lib.cargo_example('horizon-client', 'recipe_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
def key(case, native_line):
kind = case.split('\t')[0]
return kind if kind != 'craft' else 'craft ' + native_line.split('\t')[0]
def describe(case):
return case if len(case) < 1200 else case[:1200] + '...'
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', key, describe, args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()