Merge worktree-agent-a12e061d400abc3f6

This commit is contained in:
Ludovic Marie
2026-10-10 08:46:23 +02:00
40 changed files with 6156 additions and 524 deletions
+74
View File
@@ -0,0 +1,74 @@
"""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]
done = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none',
'-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', '-Xmaxerrs', '30',
'-cp', self.deps, '-d', str(self.classes), *map(str, sources)], capture_output=True, text=True)
if done.returncode:
print(done.stderr.replace(str(lab.ROOT) + '/', ''))
raise SystemExit('javac failed')
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
View File
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Compare the data-driven axe/hoe/shovel block transformers with vanilla.
The Java oracle (VanillaBlockTransformerOracle) evaluates the registry's
BlockStateProviders on a stand-in level; the Rust example
(block_transform_fixture) evaluates horizon_client::block_transform. Cases are
every block state any transformer mentions (plus a random sample of all states)
under each transformer, with a few blocks above and three clicked faces.
"""
import argparse
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
ABOVE = ['minecraft:air|', 'minecraft:cave_air|', 'minecraft:stone|', 'minecraft:water|level=0', 'minecraft:oak_slab|type=bottom,waterlogged=false']
FACES = ['up', 'down', 'north']
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--sample', type=int, default=3000)
parser.add_argument('--limit', type=int, default=4)
args = parser.parse_args()
work = lib.work_dir('block-transformer-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaBlockTransformerOracle')
vanilla.run('VanillaBlockTransformerOracle', 'dump', work / 'states.txt')
states = (work / 'states.txt').read_text().splitlines()
mentioned = set()
for path in (lib.RESOURCES / 'data/minecraft/block_transformer').glob('*.json'):
text = path.read_text()
for name in set(__import__('re').findall(r'"minecraft:([a-z_0-9]+)"', text)):
mentioned.add('minecraft:' + name)
tags = set()
for tag in ['turns_into_farmland', 'turns_into_dirt_path', 'air']:
for name in __import__('json').loads((lib.RESOURCES / 'data/minecraft/tags/block' / (tag + '.json')).read_text())['values']:
if not name.startswith('#'):
tags.add(name)
rng = random.Random(args.seed)
chosen = [s for s in states if s.split('|')[0] in mentioned or s.split('|')[0] in tags or 'copper' in s or 'lightning_rod' in s]
chosen += rng.sample(states, args.sample)
cases = []
for transformer in ['axe', 'hoe', 'shovel', 'honeycomb']:
for state in chosen:
for face in FACES:
cases.append('\t'.join([transformer, face, state, rng.choice(ABOVE)]))
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
vanilla.run('VanillaBlockTransformerOracle', work / 'cases.txt', work / 'native.txt')
lib.cargo_example('horizon-client', 'block_transform_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
lambda case, line: case.split('\t')[0] + ' ' + line.split('\t')[0][:12], None, args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+81
View File
@@ -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()
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Compare AbstractContainerMenu.clicked with vanilla's menu classes.
The Java oracle (VanillaMenuOracle) runs each case's clicks on the real menu
class with a stand-in player and level; the Rust example (menu_fixture) runs
horizon_client::menu. Cases are randomized slot contents with random click
sequences covering every ContainerInput (pickup, quick move, swap, clone,
throw, the three quick craft drags, pickup all) over the player inventory,
crafting table, chests, hopper, dispenser, shulker box and the furnaces. After
every click the slots, carried stack, data slots and drops 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
MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81,
'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46}
DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10}
COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread',
'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool',
'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin',
'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box',
'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling',
'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder',
'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath']
def quote(text):
return '"' + text + '"'
def snbt(item, count, damage=0, curse=False, potion=None):
comps = []
if potion:
comps.append('"minecraft:potion_contents":{potion:"%s"}' % potion)
if damage:
comps.append('"minecraft:damage":%d' % damage)
if curse:
comps.append('"minecraft:enchantments":{"minecraft:binding_curse":1}')
body = ',components:{%s}' % ','.join(comps) if comps else ''
return '{id:%s,count:%d%s}' % (quote(item), count, body)
class Gen:
def __init__(self, rng, items):
self.rng = rng
self.items = items
self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items]
self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k
and not k.endswith('_spawn_egg')]
def stack(self):
rng = self.rng
item = rng.choice(self.pool if rng.random() < 0.85 else self.all)
info = self.items[item]
top = info.get('minecraft:max_stack_size', 64)
damage = 0
if info.get('minecraft:max_damage') and rng.random() < 0.3:
damage = rng.randrange(1, info['minecraft:max_damage'])
count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)])
potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None
return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion)
def slots(self, size, density):
return [self.stack() if self.rng.random() < density else '-' for _ in range(size)]
def recipe(self, slots, width):
"""Fills the crafting grid (slots 1..) with a small known recipe."""
rng = self.rng
amount = lambda: rng.choice([1, 1, 2, 5, 64])
choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')],
[('iron_ingot',) * 3] * 3, [('milk_bucket',) * 3, ('sugar', 'egg', 'sugar'), ('wheat',) * 3],
[('wheat',) * 3], [('white_wool',) * 2, ('white_wool',) * 2], [('coal',), ('stick',)]]
pattern = rng.choice(choices)
if len(pattern) > width or any(len(row) > width for row in pattern):
pattern = [('oak_planks',), ('oak_planks',)]
for y, row in enumerate(pattern):
for x, name in enumerate(row):
slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1)
def ops(self, size):
rng = self.rng
out = []
for _ in range(rng.randrange(1, 9)):
kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'],
[30, 20, 8, 3, 6, 14, 6, 2])[0]
slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size)
if kind == 'PICKUP':
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
elif kind == 'QUICK_MOVE':
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
elif kind == 'SWAP':
out.append([slot, rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 40, 9, -1]), kind])
elif kind in ('CLONE', 'THROW', 'PICKUP_ALL'):
out.append([slot, rng.randrange(0, 2), kind])
elif kind == 'DRAG':
ty = rng.randrange(0, 4)
out.append([-999, 0 | ty << 2, 'QUICK_CRAFT'])
for _ in range(rng.randrange(0, 6)):
out.append([rng.randrange(size), 1 | ty << 2, 'QUICK_CRAFT'])
out.append([-999, 2 | ty << 2, 'QUICK_CRAFT'])
else:
out.append([rng.choice([slot, 999, -5]), rng.randrange(-1, 5), rng.choice(
['PICKUP', 'QUICK_MOVE', 'QUICK_CRAFT', 'SWAP', 'THROW', 'PICKUP_ALL'])])
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--cases', type=int, default=6000)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
work = lib.work_dir('menu-click-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaMenuOracle')
items = json.loads((lib.RESOURCES / 'items.json').read_text())
rng = random.Random(args.seed)
g = Gen(rng, items)
cases = []
for n in range(args.cases):
menu = list(MENUS)[n % len(MENUS)]
size = MENUS[menu]
slots = g.slots(size, rng.choice([0.1, 0.4, 0.8]))
if menu in ('inventory', 'crafting'):
slots[0] = '-'
if menu in ('inventory', 'crafting') and rng.random() < 0.6:
g.recipe(slots, 2 if menu == 'inventory' else 3)
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,
'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))],
'ops': g.ops(size)})
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt')
lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
native = (work / 'native.txt').read_text().split('\n')
rust = (work / 'rust.txt').read_text().split('\n')
def by_case(lines):
out, cur = [], []
for line in lines:
cur.append(line)
if line == 'end' or line.startswith('error-case'):
out.append(cur)
cur = []
return out
native, rust = by_case(native), by_case(rust)
bad = {}
for case, a, b in zip(cases, native, rust):
if a != b:
step = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else 0
op = case['ops'][step - 1] if 0 < step <= len(case['ops']) else None
bad.setdefault((case['menu'], op[2] if op else 'init'), []).append((case, step, a, b))
total = sum(len(v) for v in bad.values())
for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])):
print(f'{key}: {len(entries)} differing')
for case, step, a, b in entries[:args.limit]:
print(f' ops {case["ops"][:step]}\n start {a[0]}\n native {a[step]}\n rust {b[step]}')
print(f'{len(cases) - total}/{len(cases)} cases match')
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+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()