Merge parity-base into parity/platform-maths

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 04:31:39 +02:00
53 changed files with 7701 additions and 1576 deletions
+16 -1
View File
@@ -4,7 +4,7 @@
The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla
block entity (chest, trapped/copper chest and the other half of a double chest,
ender chest, enchanting table, shulker box, bell, conduit, dragon/piglin head,
decorated pot)
decorated pot, End gateway with the integrated server's copy ticking beside it)
on a stand-in client level, then per scripted step applies the block event
(triggerEvent), runs the entity's own client ticker and the renderer's
extractRenderState, printing the fields, the level calls the tick made
@@ -162,6 +162,21 @@ def cases():
step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])]
steps.append(step)
add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps)
# End gateways: the server copy's portalTick (triggerCooldown every 2400
# ticks, entities entering) sends block event 1 to the client copy, whose
# beamAnimationTick and TheEndGatewayRenderer draw the beam; saved ages
# from new to long settled, both level heights.
for i in range(40):
age = rng.choice([0, 0, 150, 2390, 4790, rng.randint(200, 10 ** 6), 2399 + 2400 * rng.randint(1, 50)])
steps = []
for t in times(rng.randint(20, 90), gaps=(1, 1, 1, 2)):
step = {'time': t, 'partial': round(rng.random(), 4)}
if rng.random() < 0.06:
step['enter'] = True
if rng.random() < 0.04:
step['event'] = [rng.choice([1, 2, 0]), rng.choice([0, 3])]
steps.append(step)
add('gateway', 'minecraft:end_gateway', steps, age=age, level=rng.choice([[0, 256], [-64, 384]]))
# Chests and ender chests: open counts from block event 1 (both halves of
# a double chest), other events ignored; the neighbour a double half
# connects to may be its other half or not (wrong block, type, facing).
+21 -5
View File
@@ -72,6 +72,11 @@ def cases():
add(f'minecraft:{color}_wall_banner[facing={f}]',
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))])
add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)])
# The loom's result preview (GuiBannerResultRenderer in a 20x40 picture in
# picture, lit with Lighting.Entry.ITEMS_FLAT): up to the loom's six layers, and 17.
for n in [0, 1, 2, 3, 6, 6, 17]:
out.append({'block': 'loom_result', 'loom': {'base': rng.choice(DYES),
'patterns': [[rng.choice(patterns), rng.choice(DYES)] for _ in range(n)]}})
for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head',
'piglin_head', 'player_head']:
wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head')
@@ -147,15 +152,26 @@ def lights():
return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7])
def items_flat_lights():
"""Lighting.Entry.ITEMS_FLAT: rotationY(-PI/8).rotateX(3PI/4) of the diffuse lights."""
def rotate(v):
a, b = -math.pi / 8, math.pi * 3 / 4
x, y, z = v
y, z = y * math.cos(b) - z * math.sin(b), y * math.sin(b) + z * math.cos(b)
return [x * math.cos(a) + z * math.sin(a), y, -x * math.sin(a) + z * math.cos(a)]
return tuple(rotate(l) for l in lights())
L0, L1 = lights()
FLAT = items_flat_lights()
def mix(normal):
def mix(normal, lit=(L0, L1)):
d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal)))
return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4)
return min(1.0, (d(lit[0]) + d(lit[1])) * 0.6 + 0.4)
def vanilla_quads(submits):
def vanilla_quads(submits, lit=(L0, L1)):
quads, other = [], []
for s in submits:
custom = s['type'] == 'submitCustomGeometry'
@@ -167,7 +183,7 @@ def vanilla_quads(submits):
q = verts[i:i + 4]
tint = q[0][3] & 0xFFFFFFFF
# Custom geometry (beacon beams) is unlit; models get the entity shader's mix light.
b = 1.0 if custom else mix(q[0][8:11])
b = 1.0 if custom else mix(q[0][8:11], lit)
ch = lambda shift: int(((tint >> shift) & 255) * b)
quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q],
'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7],
@@ -206,7 +222,7 @@ def pair(vq, rq):
def compare_case(v, r, tol):
problems = []
vq, other = vanilla_quads(v['submits'])
vq, other = vanilla_quads(v['submits'], FLAT if 'loom' in v['case'] else (L0, L1))
for s in other:
if s['type'] == 'submitText':
continue
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Compare Mob.finalizeSpawn (spawned mob gear, enchantments and state) with vanilla.
Java (VanillaFinalizeSpawnOracle) creates each case's mobs on a stand-in
ServerLevel and runs vanilla's finalizeSpawn with a seeded level random (what
finalizeSpawn reads through level.getRandom()) and seeded entity randoms; Rust
(finalize_spawn_fixture) runs horizon_client::mobs::finalize on the same case.
Cases cover every mob type, every spawn reason, peaceful to hard, game times,
inhabited times and moon phases (the local difficulty and its special
multiplier), packs sharing group data, biomes (variants, villager types,
sheep colours, rabbit and fox types), structures (black cats), roofs (camel
husk room) and chickens standing by (zombie jockeys).
Each entity created in a case, the mobs and the jockeys finalizeSpawn makes,
is compared: equipment with its enchantments, drop chances, CanPickUpLoot,
LeftHanded, persistence, age, health, attribute values, effects, variants,
the memories finalizeSpawn sets and the vehicle it rides; then the next draw
of every entity random and of the level random, which pins every draw in
between.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
REASONS = ['NATURAL', 'CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'BREEDING', 'MOB_SUMMONED', 'JOCKEY', 'EVENT',
'CONVERSION', 'REINFORCEMENT', 'TRIGGERED', 'BUCKET', 'SPAWN_ITEM_USE', 'COMMAND', 'DISPENSER', 'PATROL',
'TRIAL_SPAWNER', 'LOAD', 'DIMENSION_TRAVEL']
# Mobs whose finalizeSpawn draws, by how often the corpus picks them.
GEARED = ['zombie', 'husk', 'drowned', 'zombie_villager', 'zombified_piglin', 'skeleton', 'stray', 'bogged', 'parched',
'wither_skeleton', 'pillager', 'vindicator', 'piglin', 'piglin_brute', 'vex', 'fox', 'spider', 'illusioner',
'evoker', 'ravager', 'witch']
OTHERS = ['pig', 'cow', 'mooshroom', 'sheep', 'chicken', 'rabbit', 'horse', 'donkey', 'mule', 'llama', 'trader_llama',
'goat', 'panda', 'polar_bear', 'wolf', 'cat', 'ocelot', 'parrot', 'bee', 'turtle', 'armadillo', 'frog',
'axolotl', 'squid', 'glow_squid', 'cod', 'salmon', 'tropical_fish', 'pufferfish', 'dolphin', 'bat', 'villager',
'wandering_trader', 'iron_golem', 'snow_golem', 'creeper', 'cave_spider', 'enderman', 'endermite',
'silverfish', 'slime', 'magma_cube', 'phantom', 'hoglin', 'zoglin', 'ghast', 'blaze', 'strider', 'guardian',
'elder_guardian', 'shulker', 'camel', 'allay', 'breeze', 'sniffer', 'happy_ghast', 'warden', 'creaking',
'camel_husk', 'nautilus', 'zombie_nautilus', 'sulfur_cube', 'zombie_horse', 'skeleton_horse', 'tadpole',
'giant', 'wither']
BIOMES = ['minecraft:plains', 'minecraft:desert', 'minecraft:snowy_plains', 'minecraft:snowy_taiga', 'minecraft:taiga',
'minecraft:jungle', 'minecraft:bamboo_jungle', 'minecraft:swamp', 'minecraft:mangrove_swamp',
'minecraft:savanna', 'minecraft:badlands', 'minecraft:forest', 'minecraft:grove', 'minecraft:old_growth_pine_taiga',
'minecraft:old_growth_spruce_taiga', 'minecraft:sparse_jungle', 'minecraft:windswept_savanna',
'minecraft:mushroom_fields', 'minecraft:river', 'minecraft:frozen_river', 'minecraft:ocean',
'minecraft:warm_ocean', 'minecraft:lukewarm_ocean', 'minecraft:cold_ocean', 'minecraft:frozen_ocean',
'minecraft:ice_spikes', 'minecraft:cherry_grove', 'minecraft:pale_garden', 'minecraft:dripstone_caves',
'minecraft:lush_caves', 'minecraft:deep_dark', 'minecraft:nether_wastes', 'minecraft:crimson_forest',
'minecraft:soul_sand_valley', 'minecraft:the_end', 'minecraft:snowy_slopes', 'minecraft:frozen_peaks',
'minecraft:wooded_badlands', 'minecraft:beach', 'minecraft:snowy_beach', 'minecraft:meadow',
'minecraft:sulfur_caves']
STRUCTURES = ['minecraft:swamp_hut', 'minecraft:village_plains', 'minecraft:pillager_outpost', 'minecraft:fortress',
'minecraft:trial_chambers']
FLOORS = ['minecraft:grass_block', 'minecraft:sand', 'minecraft:stone', 'minecraft:snow_block', 'minecraft:netherrack']
def dimension(biome):
if biome in ('minecraft:nether_wastes', 'minecraft:crimson_forest', 'minecraft:soul_sand_valley'):
return 'minecraft:the_nether'
if biome == 'minecraft:the_end':
return 'minecraft:the_end'
return 'minecraft:overworld'
def corpus():
rng = random.Random(0x46494E414C)
cases = []
for k in range(int(os.environ.get('FINALIZE_SPAWN_CASES', '24000'))):
kind = rng.choice(GEARED) if rng.random() < 0.55 else rng.choice(OTHERS)
reason = rng.choice(['NATURAL'] * 10 + ['CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'COMMAND', 'SPAWN_ITEM_USE',
'TRIAL_SPAWNER', 'PATROL', 'EVENT', 'JOCKEY'] * 2 + REASONS)
biome = rng.choice(BIOMES)
kv = {
'type': f'minecraft:{kind}',
'reason': reason,
'difficulty': rng.choice(['hard', 'hard', 'normal', 'normal', 'easy', 'peaceful']),
'time': rng.choice([0, 0, 50000, 72000, 400000, 800000, 1512000, 3000000, rng.randrange(0, 4000000)]),
'inhabited': rng.choice([0, 0, 0, 100000, 1000000, 3600000, 5000000, rng.randrange(0, 4000000)]),
'phase': rng.randrange(8),
'seed': rng.randrange(-2**63, 2**63),
'eseed': rng.randrange(-2**47, 2**47),
'pack': rng.choice([1, 1, 1, 2, 3, 4, 6]),
'pos': f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.25, 0.0]):.2f},{rng.randrange(-30, 120)},'
f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.75, 0.0]):.2f}',
'biome': biome,
'dim': dimension(biome),
'floor': rng.choice(FLOORS),
}
if rng.random() < 0.15:
kv['structure'] = rng.choice(STRUCTURES)
if rng.random() < 0.2:
kv['roof'] = rng.choice([1, 2, 3])
if rng.random() < 0.15:
kv['chickens'] = rng.choice([1, 2])
if rng.random() < 0.05:
kv['monsters'] = 0
cases.append(f'case/{k} ' + ' '.join(f'{a}={b}' for a, b in kv.items()))
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
parser.add_argument('--java-only', action='store_true', help='run the oracle and stop')
args = parser.parse_args()
build = lab.LOCAL / 'rust-finalize-spawn-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs']
tested = base.source_hashes([s for s in sources if s.exists()])
inputs = build / 'inputs.txt'
cases = corpus()
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
path = build / (name + '.log')
with path.open('w', encoding='utf-8') as log:
try:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
log.flush()
raise SystemExit(f'{name} failed:\n' + path.read_text(errors='replace')[-4000:])
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaFinalizeSpawnOracle', inputs, build / 'server.txt'], 'server')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
if args.java_only:
print(f'{len(vanilla)} oracle lines')
return
halloween = vanilla[0].split()[1]
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/finalize_spawn_fixture'
run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12])
raise SystemExit(f'{len(bad)} of {len(vanilla)} lines differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged([s for s in sources if s.exists()], tested)
entities = sum(line.count(' | ') for line in vanilla) // 2
enchanted = sum(line.count('[minecraft:') for line in vanilla)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'entities': entities, 'enchanted_items': enchanted, 'sources_sha256': tested,
'scope': 'Mob.finalizeSpawn for every mob type and spawn reason: populateDefaultEquipmentSlots, '
'populateDefaultEquipmentEnchantments through the mob_spawn_equipment and pillager_spawn_crossbow '
'providers, drop chances, CanPickUpLoot, LeftHanded, the follow range spawn bonus, babies and '
'group data, jockeys (chicken, spider, strider, zombie horse, camel husk, zombie nautilus), '
'variants and sound variants, zombie attributes, spider effects, patrol leaders, villager types, '
'cube sizes, horse and llama attributes and the memories finalizeSpawn sets, with every draw of the '
'level random and of the entities\' own randoms.'})
print(f'{len(cases):,} finalizeSpawn cases match vanilla ({entities:,} entities, {enchanted:,} enchanted items)')
if __name__ == '__main__':
main()
+12
View File
@@ -77,6 +77,18 @@ def scenarios():
'player 12.5 -60 0.5',
'mob minecraft:villager 0.5 -60 0.5 0 51 persistent',
])
# The warden: idle, sniffing out a player, roaring and fighting (WardenAi).
# Without finalizeSpawn's dig cooldown a warden digs straight back down. warden_player
# and warden_cow stop before the first blow kills the player or the cow (the probe has no dying
# player, nor the attack knockback attribute or a target killed within the attacker's tick).
add('warden_digs', 140, ['mob minecraft:warden 0.5 -60 0.5 0 60'])
add('warden_alone', 400, ['mob minecraft:warden 0.5 -60 0.5 0 61 digcooldown'])
add('warden_player', 565, ['player 5.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 62 digcooldown'])
add('warden_player_far', 600, ['player 14.5 -60 3.5', 'mob minecraft:warden 0.5 -60 0.5 90 63 digcooldown'])
add('warden_creative', 300, ['player 4.5 -60 0.5 creative', 'mob minecraft:warden 0.5 -60 0.5 0 64 digcooldown'])
add('warden_persistent', 400, ['player 7.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 65 persistent digcooldown'])
add('warden_emerging', 300, ['player 6.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 66 emerge'])
add('warden_cow', 176, ['mob minecraft:warden 0.5 -60 0.5 0 67 digcooldown', 'mob minecraft:cow 4.5 -60 0.5 0 68 persistent'])
# Two villagers gossip (TradeWithVillager): what one heard of the player
# passes to the other, weakened, once in 1200 ticks; idle and at the bell.
gossips = ('gossip=player:minor_negative:100 gossip=player:major_positive:15 '
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Compare the recipe book's drawing with the vanilla client's.
Each case opens a book type (the inventory's or a crafting table's crafting
book, the furnace, blast furnace or smoker) at a GUI size, with its visible
tabs (one selected, some in their new-recipe squeeze), the search box (text,
cursor, selection, focus and cursor blink), the craftable filter, a page of
recipe collections (real recipes, some craftable, some buttons squeezing),
the alternatives overlay of one button, ghost slots, the cycling index and
the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's
widgets for that state as RecipeBookComponent.initVisuals and
RecipeBookPage.init do and records every GuiGraphicsExtractor call of their
extractRenderState, the tooltips and GhostSlots.extractRenderState, with its
pose; examples/recipe_book_render_fixture lays out the same state with
horizon_client::recipe_book_screen, which the game paints. The call lists
must agree.
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base
except ImportError:
import interaction_lab as lib
import test_model_baking_parity as baking
import test_rust_parity as base
TABS = {'crafting': 5, 'furnace': 4, 'blast_furnace': 3, 'smoker': 2}
TYPES = {'crafting': ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless'), 'furnace': ('minecraft:smelting',),
'blast_furnace': ('minecraft:blasting',), 'smoker': ('minecraft:smoking',)}
WORDS = ['', '', 'a', 'stone', 'iron ingot', 'oak', 'zzz', 'red', 'a very long search text that overflows']
def recipes_by_type():
out = {k: [] for k in TYPES}
for path in sorted((lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')):
kind = json.loads(path.read_text()).get('type')
for k, types in TYPES.items():
if kind in types:
out[k].append('minecraft:' + path.stem)
return out
def cases(count, seed):
rng = random.Random(seed)
by_type = recipes_by_type()
items = sorted(i for i in json.loads((lib.RESOURCES / 'items.json').read_text()) if i != 'minecraft:air')
out = []
for n in range(count):
kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5]
width, height = rng.choice([(427, 240), (480, 270), (640, 360), (320, 240), (378, 260), (854, 480)])
narrow = width < 379
xo = (width - 147) // 2 - (0 if narrow else 86)
yo = (height - 166) // 2
tabs = [0] + sorted(rng.sample(range(1, TABS[kind]), rng.randint(0, TABS[kind] - 1)))
selected = rng.choice(tabs)
tab_list = [{'tab': t, 'selected': t == selected, 'anim': rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)])}
for t in tabs]
total = rng.choice([0, 1, 5, 19, 20, 21, 47, 80])
pages = (total + 19) // 20
page = rng.randrange(pages) if pages else 0
filtering = rng.random() < 0.4
collections = []
for _ in range(total):
group = rng.sample(by_type[kind], rng.choice([1, 1, 1, 2, 3, 6]))
recipes = [[r, rng.random() < 0.4] for r in group]
if filtering and not any(c for _, c in recipes):
recipes[0][1] = True
collections.append({'recipes': recipes})
on_page = max(0, min(20, total - 20 * page))
value = rng.choice(WORDS)
cursor = rng.randint(0, len(value))
highlight = rng.choice([cursor, rng.randint(0, len(value))])
search = {'value': value, 'cursor': cursor, 'highlight': highlight,
'display': rng.choice([0, 0, min(cursor, rng.randint(0, len(value)))]), 'focused': rng.random() < 0.5,
'blink': rng.choice([0, 150, 450, 700])}
targets = [(xo + 11 + 25 * (i % 5) + rng.randint(0, 24), yo + 31 + 25 * (i // 5) + rng.randint(0, 24)) for i in range(on_page)]
targets += [(xo + 115, yo + 20), (xo + 95, yo + 140), (xo + 40, yo + 140), (xo + 30, yo + 18), (xo - 20, yo + 40),
(rng.randint(0, width), rng.randint(0, height))]
case = {'type': kind, 'grid': 2 if rng.random() < 0.5 else 3, 'width': width, 'height': height, 'narrow': narrow,
'mouse': list(rng.choice(targets)), 'index': rng.choice([0, 0, 1, 2, 5, 13, 60]), 'filtering': filtering,
'tabs': tab_list, 'search': search, 'collections': collections, 'page': page,
'buttonAnims': [rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)]) for _ in range(on_page)]}
multi = [i for i in range(on_page) if sum(1 for _, c in collections[20 * page + i]['recipes'] if c or not filtering) > 1]
if multi and rng.random() < 0.4:
case['overlay'] = rng.choice(multi)
if rng.random() < 0.4:
left, top = (width - 176) // 2, (height - 166) // 2
slots = [(124, 35, True)] + [(30 + 18 * (i % 3), 17 + 18 * (i // 3), False) for i in range(9)]
if kind != 'crafting':
slots = [(116, 35, True), (56, 17, False)]
case.update({'left': left, 'top': top, 'big': rng.random() < 0.7,
'ghost': [{'x': x, 'y': y, 'result': r, 'items': rng.sample(items, rng.choice([1, 1, 2, 4]))}
for x, y, r in rng.sample(slots, rng.randint(1, len(slots)))]})
out.append(case)
return out
def same(a, b):
"""Calls agree: every field exactly, poses within float printing."""
if a is None or b is None or set(a) != set(b):
return False
return all(all(abs(x - y) <= 1e-3 for x, y in zip(a[k], b[k])) if k == 'm' else a[k] == b[k] for k in a)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=29)
parser.add_argument('--cases', type=int, default=600)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
work = lib.work_dir('recipe-book-render-parity')
classes = work / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps,
'-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'ParityFont', 'VanillaRecipeBookScreenOracle'))],
capture_output=True, text=True)
if done.returncode:
print(done.stderr[-4000:])
sys.exit('javac failed')
chosen = cases(args.cases, args.seed)
inputs = work / 'cases.jsonl'
inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaRecipeBookScreenOracle',
str(inputs), str(work / 'vanilla.jsonl')], capture_output=True, text=True)
if run.returncode:
print(run.stderr[-4000:])
sys.exit('oracle failed')
lib.cargo_example('horizon-client', 'recipe_book_render_fixture', lib.RESOURCES, inputs, work / 'rust.jsonl')
vanilla = [json.loads(l) for l in (work / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen))
errors, failures, passed = {}, {}, 0
for case, v, r in zip(chosen, vanilla, rust):
if 'error' in v:
errors.setdefault(case['type'], v['error'])
continue
a, b = v['draws'], r['draws']
bad = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or not same(a[i], b[i])), None)
if bad is None:
passed += 1
else:
failures.setdefault(case['type'], []).append((case, bad, a[bad] if bad < len(a) else None, b[bad] if bad < len(b) else None))
for kind, error in sorted(errors.items()):
print(f'ORACLE ERROR {kind}: {error[:1500]}')
for kind, items in sorted(failures.items()):
print(f'MISMATCH {kind}: {len(items)} cases')
for case, i, x, y in items[:args.limit]:
brief = {k: v for k, v in case.items() if k not in ('collections',)}
print(f' {json.dumps(brief)[:700]}')
print(f' call {i}: vanilla {json.dumps(x)}')
print(f' call {i}: horizon {json.dumps(y)}')
print(f'{passed}/{len(chosen)} cases match')
if errors or failures:
sys.exit(1)
print('recipe book render parity ok')
if __name__ == '__main__':
main()