Merge origin/main into t3/fix-critical-hit-particles

Keep both critical-hit and sculk container regressions.

Co-Authored-By: OpenCode (agentrouter/gpt-6.1-sol) <noreply@openai.com>
This commit is contained in:
rdbtCVS
2026-10-26 04:14:11 +00:00
188 changed files with 15854 additions and 3727 deletions
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Compare two isolated preparations with a batched, runtime-only release preparation.
Uses only locally imported pinned Minecraft files. Run after compile-exporters and copy its
server/, client/ and manifest.json to exporters/. Byte differences are accepted only where
both isolated runs also differ and normalize identically (known exporter noise).
"""
import argparse
import hashlib
import json
import os
import re
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
import time
ROOT = Path(__file__).resolve().parents[1]
def hashes(folder):
return {str(p.relative_to(folder)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in folder.rglob('*') if p.is_file() and p.suffix != '.log'
and not {'classes', 'client-classes'} & set(p.relative_to(folder).parts)
and p.name != 'horizon-resources.json'}
def normalize(path):
value = json.loads(path.read_text())
if path.name == 'block-behaviours.json':
# JVM-assigned lambda class addresses are printed as opaque field values.
def clean(node):
if isinstance(node, str):
return re.sub(r'\$\$Lambda/0x[0-9a-fA-F]+', '$$Lambda/<address>', node)
if isinstance(node, list):
return [clean(item) for item in node]
if isinstance(node, dict):
return {key: clean(item) for key, item in node.items()}
return node
value = clean(value)
elif path.name == 'creative-inventory.json':
for tab in value['tabs']:
if 'tags' in tab:
tab['tags'] = [sorted(tags) for tags in tab['tags']]
return value
def verify(folders):
a, b, batched = [hashes(folder) for folder in folders]
if a.keys() != b.keys() or a.keys() != batched.keys():
raise SystemExit('Resource file sets differ')
known = {'render-definitions.json', 'block-behaviours.json', 'creative-inventory.json'}
noise = [name for name in a if a[name] != b[name] or a[name] != batched[name]]
differences = []
for name in noise:
if name not in known:
differences.append(name)
else:
x, y, z = [normalize(folder / name) for folder in folders]
if x != y or x != z:
differences.append(name)
manifests = []
for folder, raw in zip(folders, [a, b, batched]):
replacements = {raw[name]: f'normalized:{name}' for name in noise}
def clean(node):
if isinstance(node, str):
return replacements.get(node, node)
if isinstance(node, list):
return [clean(item) for item in node]
if isinstance(node, dict):
return {key: clean(item) for key, item in node.items()}
return node
manifests.append(clean(json.loads((folder / 'horizon-resources.json').read_text())))
if manifests[0] != manifests[1] or manifests[0] != manifests[2]:
differences.append('horizon-resources.json')
print(f'Normalized exporter noise: {noise}')
if differences:
raise SystemExit(f'Resources differ: {differences}')
print(f'PASS: all {len(a)} resource files match, with only known noise normalized')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary', type=Path, required=True)
parser.add_argument('--work', type=Path)
args = parser.parse_args()
binary = args.binary.resolve()
with tempfile.TemporaryDirectory(prefix='prepare-exporters-') as temporary:
work = args.work.resolve() if args.work else Path(temporary)
work.mkdir(parents=True, exist_ok=True)
# Freeze the tested executable even if a developer rebuilds concurrently.
frozen = work / binary.name
shutil.copy2(binary, frozen)
binary = frozen
results = []
times = []
for name in ['isolated-1', 'isolated-2', 'batched']:
folder = work / name
folder.mkdir()
shutil.copyfile(ROOT / 'research-lock.json', folder / 'research-lock.json')
shutil.copytree(ROOT / 'mods/horizon/src/test/java', folder / 'mods/horizon/src/test/java')
shutil.copytree(ROOT / 'exporters', folder / 'exporters')
(folder / '.local').mkdir()
(folder / '.local/minecraft').symlink_to((ROOT / '.local/minecraft').resolve(), target_is_directory=True)
env = dict(os.environ)
env.pop('HORIZON_PREPARE_ISOLATED', None)
if name.startswith('isolated'):
env['HORIZON_PREPARE_ISOLATED'] = '1'
else:
# An actual runtime-only home: no javac in bin. Java resolves its own libraries.
java = Path(shutil.which('java')).resolve()
runtime = folder / 'runtime'
(runtime / 'bin').mkdir(parents=True)
trace = folder / 'java-invocations.txt'
wrapper = runtime / 'bin' / java.name
wrapper.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> '
+ shlex.quote(str(trace)) + '\nexec '
+ shlex.quote(str(java)) + ' "$@"\n')
wrapper.chmod(0o755)
env['JAVA_HOME'] = str(runtime)
env['PATH'] = str(runtime / 'bin')
started = time.monotonic()
with (work / f'{name}.log').open('w') as log:
subprocess.run([str(binary), '--root', str(folder)], cwd=folder, env=env,
stdout=log, stderr=subprocess.STDOUT, check=True, timeout=1200)
if name == 'batched':
launches = [line for line in trace.read_text().splitlines() if line != '-version']
if len(launches) != 5:
raise SystemExit(f'Expected 5 exporter/data-generator JVMs, got {len(launches)}')
print(f'Runtime-only preparation: {len(launches)} JVM launches', flush=True)
text = (work / f'{name}.log').read_text()
if 'Compiling ' in text:
raise SystemExit(f'{name} unexpectedly needed a compiler')
resources = next((folder / '.local/horizon-client').iterdir())
results.append(resources)
times.append(round(time.monotonic() - started, 2))
print(f'{name}: {times[-1]}s, prepared', flush=True)
verify(results)
print(f'Isolated {times[:2]}s, batched {times[2]}s')
if __name__ == '__main__':
main()
+22 -1
View File
@@ -628,7 +628,9 @@ def world_misc():
cmd('/fill 0 210 0 2 212 2 minecraft:glass keep'),
cmd('/fill 0 210 0 2 212 2 minecraft:dirt replace #minecraft:base_stone_overworld'),
cmd('/fill 0 210 0 2 212 2 minecraft:air strict'),
cmd('/fill 0 210 0 100 300 100 minecraft:stone'),
# A connected server loads more terrain than the oracle's 5x5 core.
# Keep the far corner unambiguously unloaded in both executions.
cmd('/fill 0 210 0 1000 300 1000 minecraft:stone'),
cmd('/setblock 0 211 0 minecraft:oak_sign{front_text:{messages:["a","b","c","d"]}}'),
cmd('/data get block 0 211 0 front_text.messages'),
cmd('/clone 0 211 0 0 211 0 1 211 1 replace move'),
@@ -831,6 +833,9 @@ def functions_and_packs():
def ticking():
return [
# Isolate named-stream commands from earlier loot rolls, including
# ocean vegetation updated while asynchronous terrain loads settle.
*setup('/random reset *'),
cmd('/tick query'),
cmd('/tick rate 40'),
cmd('/tick query'),
@@ -1063,9 +1068,25 @@ def test_command():
]
def server_clock():
"""Only explicit tick operations advance the script's authoritative clock."""
return [
*setup('/scoreboard objectives add harness_clock dummy',
'/execute store result score before harness_clock run time query gametime'),
{'op': 'tick', 'n': 3},
*setup('/execute store result score elapsed harness_clock run time query gametime',
'/scoreboard players operation elapsed harness_clock -= before harness_clock'),
cmd('/scoreboard players get elapsed harness_clock'),
# The connected owner is the only player; @s and @a use the same body.
cmd('/execute as @a run say connected owner'),
*setup('/scoreboard objectives remove harness_clock'),
]
def groups():
return [
('setup', group_setup()),
('server clock', server_clock()),
('client commands', client_commands()),
('game state', game_state()),
('player state', player_state()),
+74 -9
View File
@@ -247,9 +247,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
sends each target its packet).
- hero-trading: the host and the guest each trade 20 wheat for an emerald, paying 14 with Hero I
and 12 with Hero III; clearing the effect restores the ordinary price (#1365).
- falling: an item and a falling block the host summons high up fall smoothly on the guest, a
little further every tick between the server's updates (every 20 ticks), as their own
client tick moves them (they used to hang, then jump down once a second, #1568).
- falling: an item, a falling block and primed TNT the host summons high up fall smoothly on the
guest, a little further every tick between the server's updates (every 20 ticks, 10 for
TNT), as their own client tick moves them (they used to hang, then jump down once a
second, #1568), and the TNT's fuse burns down on the guest too.
- instant_digging: an instant survival break leaves no repeated stone hit sounds or stale server dig (#1908).
- replant: flowers and crops replanted after a short harvest click stay planted for both players;
the server forgets the completed instant break (#1880).
@@ -6186,10 +6187,11 @@ CHECK_FNS.update(large_chest=check_large_chest)
def check_falling(host, guest, out):
"""ItemEntity and FallingBlockEntity tick on a client too (gravity, collisions, drag), and their
position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an item's
and a falling block's position every 20 ticks, so between two updates the guest's own tick is
what moves them: sampled every 2 ticks over the first 16, both are lower nearly every time."""
"""ItemEntity, FallingBlockEntity and PrimedTnt tick on a client too (gravity, collisions, drag),
and their position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an
item's and a falling block's position every 20 ticks and TNT's every 10, so between two updates
the guest's own tick is what moves them: sampled every 2 ticks over the first 16, all three are
lower nearly every time. The TNT's fuse (sent once, at spawn) counts down on the guest too."""
x, y, z = (int(v // 1) for v in pos_of(guest))
top = y + 30
tag = 'falling_e2e'
@@ -6198,7 +6200,10 @@ def check_falling(host, guest, out):
f'{{Tags:["{tag}"],Item:{{id:"minecraft:diamond",count:1}},PickupDelay:32767}}')
host('command', command=f'summon minecraft:falling_block {x + 2.5} {top} {z - 0.5} '
f'{{Tags:["{tag}"],BlockState:{{Name:"minecraft:sand"}},DropItem:0b}}')
heights = {'item': [], 'falling block': []}
# Horizon's selectors don't see primed TNT yet: its fuse ends it in the air, 19 blocks down.
host('command', command=f'summon minecraft:tnt {x + 4.5} {top} {z + 0.5} {{fuse:34s}}')
heights = {'item': [], 'falling block': [], 'primed tnt': []}
fuses = []
try:
for _ in range(8):
items = [e['pos'][1] for e in guest.raw('entities', 48, 'minecraft:item')['entities']
@@ -6206,8 +6211,12 @@ def check_falling(host, guest, out):
blocks = [o['position'][1] for o in guest('status')['projectiles']
if o.get('kind') == 'minecraft:falling_block'
and abs(o['position'][0] - x - 2.5) < 0.5 and abs(o['position'][2] - z + 0.5) < 0.5]
tnts = [o for o in guest('status')['projectiles'] if o.get('kind') == 'minecraft:tnt'
and abs(o['position'][0] - x - 4.5) < 0.5 and abs(o['position'][2] - z - 0.5) < 0.5]
heights['item'].append(items[0] if items else None)
heights['falling block'].append(blocks[0] if blocks else None)
heights['primed tnt'].append(tnts[0]['position'][1] if tnts else None)
fuses.append(tnts[0]['fuse'] if tnts else None)
guest.wait(2)
guest.shot(out, 'falling')
finally:
@@ -6219,7 +6228,24 @@ def check_falling(host, guest, out):
drops = sum(b < a for a, b in zip(seen, seen[1:]))
# A tick or two can pass between two samples with no move; never most of them.
assert drops >= len(seen) - 2, f'the {name} fell in {drops} of {len(seen) - 1} samples: {heights}'
return heights
# The server sends the TNT's fuse with each move, so each sample says how many ticks it has
# fallen from rest: snapped to the server's place and ticking on, the guest has it exactly
# there (it used to trail two ticks behind, interpolating towards each update).
fell = [(h, 34 - f) for h, f in zip(heights['primed tnt'], fuses) if f is not None]
assert fell and fell[-1][1] > fell[0][1], f'the TNT\'s fuse on the guest: {fuses}'
off = max(abs(h - tnt_fall(top, n)) for h, n in fell)
assert off < 0.01, f'the guest\'s TNT is {off:.3f} off its fall (height, ticks): {fell}'
return {**heights, 'fuse': fuses}
def tnt_fall(top, ticks):
"""PrimedTnt.tick in open air from rest: its height after `ticks` ticks."""
y, v = top, 0.0
for _ in range(ticks):
v -= 0.04
y += v
v *= 0.98
return y
CHECKS += ['falling']
@@ -6548,6 +6574,45 @@ CHECKS += ['critical-hits']
CHECK_FNS['critical-hits'] = check_critical_hits
def check_sculk_container(host, guest, out):
"""A real guest's container interaction emits a server game event. Both
clients see the sensor and the non-summoning shrieker activate and reset.
The component oracle separately controls warning levels and seeded mobs.
"""
x, y, z = (int(v // 1) for v in pos_of(guest))
chest, sensor, shrieker = (x + 2, y, z), (x + 3, y, z), (x + 4, y, z)
guest('command', command='gamemode survival')
for at, block in ((chest, 'chest'), (shrieker, 'sculk_shrieker'), (sensor, 'sculk_sensor')):
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}')
guest.wait(60)
seen = {}
# Keep the sensor's 30-tick active window observable while both clients
# acknowledge the container and the control socket inspects them.
host('command', command='tick rate 4')
try:
guest.raw('interact', *chest)
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
for game in (host, guest):
active = wait_state(game, sensor, 'sculk_sensor_phase', 'active', 40)
shrieking = wait_state(game, shrieker, 'shrieking', 'true', 40)
seen[game.name] = (active, shrieking)
assert all(s == ('active', 'true') for s in seen.values()), seen
guest.raw('key', 'esc', 'tap')
for game in (host, guest):
assert wait_state(game, sensor, 'sculk_sensor_phase', 'inactive', 160) == 'inactive', seen
assert wait_state(game, shrieker, 'shrieking', 'false', 160) == 'false', seen
finally:
host('command', command='tick rate 20')
if guest('state').get('screen') == 'container':
guest.raw('key', 'esc', 'tap')
for at in (sensor, shrieker, chest):
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
return seen
CHECKS += ['sculk_container']
CHECK_FNS['sculk_container'] = check_sculk_container
def check_replant(host, guest, out):
"""Instant breaks leave no server dig that can destroy a replacement (#1880).
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""Horizon's client on a vanilla 26.3 dedicated server, end to end.
A vanilla server (the pinned server jar, offline mode, a flat world) and one Horizon game joined to it,
driven by horizon-ctl. The server's console does what a server or its plugins do; the checks read what
the game shows and what reaches the server (its console and, for custom click actions, its debug log).
python3 tools/server_e2e.py --bin-dir target/fast # every check
python3 tools/server_e2e.py --bin-dir target/fast --check dialog
Checks:
- dialog: `/dialog show` with a multi-action dialog (a message, a text and a boolean input, three
buttons): the game shows it with its inputs and buttons, the text typed and the box ticked
go back in a command template (`trigger`, run by the server) and in a custom action's
payload (the server's "Received custom click action" line), `wait_for_response` leaves the
waiting screen, and `/dialog clear` closes a dialog (servers used to see nothing: the game
dropped the packets).
- titles: a chest named with styles (`CustomName`, as a plugin's menu is): its screen's title keeps
the colours and bold (it used to be flattened to plain grey).
The game runs with fresh HORIZON_HOME, launcher and XDG folders and without audio. Screenshots and both
logs go to --out.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
import test_rust_parity as base # noqa: E402
from agent_control_e2e import Failed # noqa: E402
from lan_e2e import Game # noqa: E402
from test_dedicated_server_parity import Server # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
PLAYER = 'Steve'
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
'level-type': 'minecraft\\:flat',
'generate-structures': 'false',
'spawn-protection': '0',
'view-distance': '3',
'simulation-distance': '3',
'pause-when-empty-seconds': '-1',
}
# MinecraftServer.handleCustomClickAction logs at debug level: the console shows that logger's debug lines.
LOG4J = """<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders><Console name="out" target="SYSTEM_OUT"><PatternLayout pattern="[%level] %msg%n"/></Console></Appenders>
<Loggers>
<Logger name="net.minecraft.server.MinecraftServer" level="debug"/>
<Root level="info"><AppenderRef ref="out"/></Root>
</Loggers>
</Configuration>
"""
def snbt(value):
"""A JSON value as SNBT (strings quoted, booleans as bytes)."""
if isinstance(value, bool):
return '1b' if value else '0b'
if isinstance(value, str):
return json.dumps(value)
if isinstance(value, list):
return '[' + ','.join(snbt(v) for v in value) + ']'
if isinstance(value, dict):
return '{' + ','.join(f'{k}:{snbt(v)}' for k, v in value.items()) + '}'
return str(value)
def check_dialog(server, game, out):
server.console('scoreboard objectives add answer trigger')
server.console(f'scoreboard players enable {PLAYER} answer')
dialog = {
'type': 'minecraft:multi_action',
'title': {'text': 'Sign in', 'color': 'gold'},
'body': {'type': 'minecraft:plain_message', 'contents': 'Pick a number.'},
'inputs': [
{'type': 'minecraft:text', 'key': 'number', 'label': 'Number'},
{'type': 'minecraft:boolean', 'key': 'agree', 'label': 'Agree', 'on_true': '1', 'on_false': '0'},
],
'actions': [
{'label': 'Send', 'action': {'type': 'minecraft:dynamic/run_command',
'template': 'trigger answer set $(number)$(agree)'}},
{'label': 'Submit', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:e2e',
'additions': {'tag': 'x'}}},
{'label': 'Wait', 'action': {'type': 'minecraft:dynamic/custom', 'id': 'horizon:wait'}},
],
'after_action': 'none',
'pause': False, # a pausing dialog must close after an action
}
shown = {}
server.console(f'dialog show {PLAYER} {snbt(dialog)}')
game.raw('wait-for', 'screen', 'dialog', '--timeout', 30)
state = game('state')
shown['shown'] = state['dialog']['open']
assert shown['shown']['title'] == 'Sign in', shown
assert [i['key'] for i in shown['shown']['inputs']] == ['number', 'agree'], shown
assert shown['shown']['buttons'] == ['Send', 'Submit', 'Wait'], shown
game.shot(out, 'dialog')
# The text, the box, then the command the template makes of them.
game.raw('type', '4')
game.raw('click', 'agree')
game.raw('click', 'send')
time.sleep(1)
server.console(f'scoreboard players get {PLAYER} answer')
server.wait_for(rf'{PLAYER} has 41 \[answer\]', timeout=30)
shown['trigger'] = 41
# A custom action: its additions and every input's tag.
game.raw('click', 'submit')
server.wait_for(r'Received custom click action horizon:e2e with payload', timeout=30)
line = next(l for l in server.lines if 'horizon:e2e' in l)
shown['custom'] = line.split('payload ', 1)[1]
for part in ('agree:1b', 'number:"4"', 'tag:"x"'):
assert part in shown['custom'], shown
# after_action none: still open. Then clear it.
assert game('state')['dialog']['open'], 'the dialog closed after an action with after_action none'
server.console(f'dialog clear {PLAYER}')
game.raw('wait-for', 'screen', 'playing', '--timeout', 30)
# wait_for_response: the waiting screen until the server answers (here, never).
server.console(f'dialog show {PLAYER} {snbt(dict(dialog, after_action="wait_for_response"))}')
game.raw('wait-for', 'screen', 'dialog', '--timeout', 30)
game.raw('click', 'wait')
server.wait_for(r'Received custom click action horizon:wait', timeout=30)
shown['waiting'] = game('state')['dialog']['screen']
game.shot(out, 'waiting')
assert shown['waiting'] == 'waiting_for_response', shown
# Its Back works after 5 s, and so does Escape (clear_dialog leaves it open, as in vanilla).
time.sleep(5.5)
game.raw('key', 'esc', 'tap')
game.raw('wait-for', 'screen', 'playing', '--timeout', 10)
return shown
def check_titles(server, game, out):
# AbstractContainerScreen draws the title the server sent, its styles included (#1645). A named
# chest is what a plugin's menu looks like: its CustomName is the open_screen title.
x, y, z = (int(v // 1) for v in game('state')['player']['position'])
chest = (x + 2, y, z)
name = [{'text': 'Server ', 'color': 'gold', 'bold': True}, {'text': 'Selector', 'color': 'aqua'}]
server.console(f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest{{CustomName:{snbt(name)}}}')
game.wait(10)
game.raw('interact', *chest)
game.raw('wait-for', 'screen', 'container', '--timeout', 30)
game.wait(5)
title = game('screen').get('title')
game.shot(out, 'titles')
game.raw('key', 'esc', 'tap')
# A list is its first component with the rest as its children: they inherit its bold.
want = [{'text': 'Server ', 'color': '#FFAA00', 'bold': True, 'italic': False},
{'text': 'Selector', 'color': '#55FFFF', 'bold': True, 'italic': False}]
assert title == want, title
return {'title': title}
CHECKS = {'dialog': check_dialog, 'titles': check_titles}
def run(bins, out, checks):
lock, jars, libraries = base.verify_artifacts()
work = Path(tempfile.mkdtemp(prefix='hz-server-e2e-'))
port = lab.free_port()
directory = work / 'server'
directory.mkdir()
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
(directory / 'eula.txt').write_text('eula=true\n')
(work / 'log4j2.xml').write_text(LOG4J)
classpath = os.pathsep.join(map(str, [jars['server'], *libraries]))
server = Server(['java', '-Xmx2g', f'-Dlog4j.configurationFile={work / "log4j2.xml"}', '-cp', classpath,
'net.minecraft.server.Main', 'nogui'], directory, 'vanilla')
game = Game('client', bins / 'horizon-ctl', lab.RESOURCES.resolve())
for key in ('XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'HORIZON_LAUNCHER_HOME'):
game.d.env[key] = str(game.work / key.lower())
game.d.env['HORIZON_LAUNCHER_NO_SELF_UPDATE'] = '1'
results = {}
try:
server.wait_for(r'Done \(')
server.console('gamerule spawn_mobs false')
game('launch', wait=False, offscreen=sys.platform == 'darwin')
game.raw('connect', f'127.0.0.1:{port}', PLAYER)
game.raw('wait-for', 'loaded', '--timeout', 300)
server.wait_for(rf'{PLAYER} joined the game')
server.console(f'op {PLAYER}')
game.wait(20)
for name in checks:
try:
results[name] = {'pass': True, 'detail': CHECKS[name](server, game, out)}
except (Failed, AssertionError, StopIteration, KeyError) as e:
results[name] = {'pass': False, 'detail': repr(e)}
print(f'[server] {name}: {"PASS" if results[name]["pass"] else "FAIL"} {results[name]["detail"]}')
finally:
(out / 'client.log').write_text(game.close())
server.stop()
shutil.copy(server.log_path, out / 'server.log')
shutil.rmtree(game.work, ignore_errors=True)
shutil.rmtree(work, ignore_errors=True)
return results
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
parser.add_argument('--check', action='append', choices=list(CHECKS), help='run only these checks (repeatable)')
parser.add_argument('--out', default=str(ROOT / '.local/server-e2e'), help='screenshots and logs go here')
args = parser.parse_args()
if args.bin_dir:
bins = Path(args.bin_dir).resolve()
else:
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
cwd=ROOT, check=True)
bins = ROOT / 'target/fast'
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
results = run(bins, out, args.check or list(CHECKS))
print(json.dumps(results, indent=1))
sys.exit(0 if results and all(r['pass'] for r in results.values()) else 1)
if __name__ == '__main__':
main()
+2 -2
View File
@@ -4,7 +4,7 @@
Java (VanillaCommandExecOracle) starts a stand-in integrated server: a real
MinecraftServer with a generated world, Commands.CommandSelection.INTEGRATED
and one single-player owner named Player. Rust runs the same script through
the Horizon client headless (HORIZON_COMMAND_SCRIPT). Both run each command as
Horizon's integrated server with a connected headless client (HORIZON_COMMAND_SCRIPT). Both run each command as
the player through Commands.performPrefixedCommand and record every system or
chat message the player receives (text and resolved style: colour, bold,
italic, underlined, strikethrough, obfuscated) together with the results the
@@ -82,7 +82,7 @@ def main():
rust_dir = build / 'rust'
shutil.rmtree(rust_dir, ignore_errors=True)
rust_dir.mkdir()
env = lab.game_env(HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
env = lab.game_env(HORIZON_SERVER_THREAD=1, HORIZON_PLAYER_NAME="Player", HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
run([binary, '--resources', lab.RESOURCES, '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env)
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]
+1 -1
View File
@@ -5,7 +5,7 @@ A dispenser or dropper at the origin faces a random direction and holds the
case's items; the block in front (and below it) comes from a palette of blocks
the behaviours care about, and some cases put a target entity in front. Vanilla
`DispenserBlock.dispenseFrom` runs over the headless level of the block update
oracle (`VanillaDispenserOracle`); Horizon runs its game glue in a headless game
oracle (`VanillaDispenserOracle`); Horizon runs its game glue as a component probe on a server thread
(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, container contents,
spawned entities (type, position, motion), the targets afterwards, level events,
sounds, game events and the level random. Motion drawn from an entity's own
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""A connected client advances ghast fireballs between tracker packets.
AbstractHurtingProjectile.tick/applyInertia run on clients as well as servers.
Like lan_e2e's falling-entity check, sample motion more often than the tracker
interval; an interpolation-only client stalls for most of that interval.
"""
import json
import math
import subprocess
import lab
import lan_e2e as lan
def check_motion(host, guest, out):
x, y, z = (math.floor(v) for v in lan.pos_of(guest))
for game in (host, guest):
game('command', command='gamemode creative')
tag = 'remote_fireball_parity'
host('command', command=f'fill {x + 2} {y + 18} {z - 1} {x + 48} {y + 23} {z + 1} minecraft:air')
host('command', command=f'summon minecraft:fireball {x + 3.5} {y + 20} {z + 0.5} '
f'{{Tags:["{tag}"],Motion:[0.1d,0.0d,0.0d]}}')
samples = []
try:
for _ in range(8):
balls = [p for p in guest('status')['projectiles'] if p['kind'] == 'LargeFireball']
samples.append(balls[0]['position'][0] if balls else None)
guest.wait(2)
finally:
host('command', command=f'kill @e[tag={tag}]')
seen = [p for p in samples if p is not None]
assert len(seen) >= 6, f'fireball visible in only {len(seen)} samples: {samples}'
moves = sum(b != a for a, b in zip(seen, seen[1:]))
assert moves >= len(seen) - 2, f'fireball stalled between tracker updates: {samples}'
return {'positions': samples}
def main():
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client',
'--bin', 'horizon-client', '--bin', 'horizon-ctl'], cwd=lab.ROOT, check=True)
metadata = json.loads(subprocess.check_output(
['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=lab.ROOT, text=True))
ctl = lab.ROOT / metadata['target_directory'] / 'fast' / 'horizon-ctl'
lan.CHECK_FNS['remote-fireball'] = check_motion
# Use the runner's current display (xvfb on Linux), with fresh isolated homes.
lan.game_env = lambda _screen, home: lab.game_env(
HORIZON_HOME=home, HORIZON_TELEMETRY_URL='off')
reports = {}
for threaded in (True, False):
lan.SERVER_THREAD = threaded
mode = 'server-thread' if threaded else 'in-frame'
out = lab.LOCAL / 'remote-fireball-parity' / mode
out.mkdir(parents=True, exist_ok=True)
# lan.Game launches each client with lab.game_env and private scratch homes.
reports[mode] = lan.run(ctl, out, lab.RESOURCES.resolve(), ['remote-fireball'])
lab.write_json(lab.LOCAL / 'remote-fireball-parity' / 'report.json', reports)
assert all(r['pass'] for mode in reports.values() for r in mode.values()), reports
if __name__ == '__main__':
main()
+1 -1
View File
@@ -5,7 +5,7 @@ The Java oracle (VanillaSculkOracle) runs each scenario in a real, headless, fla
level: it builds the blocks, places the player (with a warning level) and entities, and ticks the
level in ServerLevel.tick's order while scripted game events and block changes happen at given
ticks. Horizon runs the same scenarios through its game code (`HORIZON_SCULK_FIXTURE`, the
same functions the game ticks). Both print, per tick, what changed at the watched blocks (state,
same server phases, with synthetic player and entity state). Both print, per tick, what changed at the watched blocks (state,
vibration, selector, last frequency, warning level, charge cursors), sounds, level events, the
player's warden warning level and darkness, new entities, and the level random. The harness
reports each scenario's first differing tick.
+5
View File
@@ -54,6 +54,9 @@ QUIET = [
]
CASES = {'broadcast': ({}, BROADCAST), 'quiet': ({'broadcast-console-to-ops': 'false'}, QUIET)}
STEP_SECONDS = 2.0
# Steps whose reply can take longer than a step: the next step waits for this console line first. A loaded machine
# took 2 s to save vanilla's world, and the transcript ended before "Saved the game".
WAIT_FOR = {'console-save': r'System chat: Saved the game'}
def run_side(label, case, server_command, client_command, build, world):
@@ -88,6 +91,8 @@ def run_side(label, case, server_command, client_command, build, world):
server.console(command)
for action in actions:
tell(action)
if step in WAIT_FOR:
server.wait_for(WAIT_FOR[step], timeout=120)
time.sleep(STEP_SECONDS)
tell('end')
client.wait(timeout=60)
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Both players' ordinary walking activates a sculk sensor on the server.
Exercise Entity.move movement emission through real client input, alongside
sculk's deterministic vanilla oracle. Check the integrated-server and in-frame
hosts: the guest always uses the server-player path.
"""
import json
import math
import subprocess
import lab
import lan_e2e as lan
def until(game, observe, predicate, ticks=100):
value = observe()
for _ in range(ticks):
if predicate(value):
return value
game.wait(1)
value = observe()
assert predicate(value), value
return value
def check_walk(host, guest, out, role):
player = host if role == 'host' else guest
hx, y, hz = (math.floor(v) for v in lan.pos_of(host))
x, z = hx + 6, hz + (-8 if role == 'host' else 8)
sensor = (x + 3, y, z + 1)
player('command', command='gamemode survival')
host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 5} {y - 1} {z + 5} minecraft:stone')
host('command', command=f'fill {x - 2} {y} {z - 2} {x + 5} {y + 3} {z + 5} minecraft:air')
start = (x + 0.5, y, z + 0.5)
player('command', command=f'tp @s {start[0]} {start[1]} {start[2]} 0 0')
until(player, lambda: lan.pos_of(player), lambda p: math.dist(p, start) < 0.1)
player.raw('look', 0, 0)
player.wait(2)
host('command', command=f'setblock {sensor[0]} {sensor[1]} {sensor[2]} minecraft:sculk_sensor')
phase = lambda game: game.raw('getblock', *sensor)['block']
try:
until(host, lambda: phase(host), lambda s: 'sculk_sensor_phase=inactive' in s)
player.wait(10)
assert 'sculk_sensor_phase=inactive' in phase(host), 'setup activated the sensor'
player.raw('key', 'w', 'down')
try:
player.wait(15)
finally:
player.raw('key', 'w', 'up')
moved = {'client': math.dist(lan.pos_of(player), start),
'server': math.dist(lan.server_player(host, player)['position'], start)}
assert all(d > 1 for d in moved.values()), moved
for viewer in (host, guest):
until(viewer, lambda: phase(viewer), lambda s: 'sculk_sensor_phase=active' in s, ticks=85)
return {'moved': moved, 'phase': phase(host)}
finally:
player.raw('key', 'w', 'up')
host('command', command=f'fill {x - 2} {y} {z - 2} {x + 5} {y + 3} {z + 5} minecraft:air')
def main():
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client',
'--bin', 'horizon-client', '--bin', 'horizon-ctl'], cwd=lab.ROOT, check=True)
metadata = json.loads(subprocess.check_output(
['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=lab.ROOT, text=True))
ctl = lab.ROOT / metadata['target_directory'] / 'fast' / 'horizon-ctl'
checks = ['sculk-walk-host', 'sculk-walk-guest']
for role, name in zip(('host', 'guest'), checks):
lan.CHECK_FNS[name] = lambda h, g, o, role=role: check_walk(h, g, o, role)
# Use the runner's current display (xvfb on Linux), with fresh isolated homes.
lan.game_env = lambda _screen, home: lab.game_env(
HORIZON_HOME=home, HORIZON_TELEMETRY_URL='off')
reports = {}
for threaded in (True, False):
lan.SERVER_THREAD = threaded
mode = 'server-thread' if threaded else 'in-frame'
out = lab.LOCAL / 'server-player-sculk-parity' / mode
out.mkdir(parents=True, exist_ok=True)
# lan.Game launches each client with lab.game_env and private scratch homes.
reports[mode] = lan.run(ctl, out, lab.RESOURCES.resolve(), checks)
lab.write_json(lab.LOCAL / 'server-player-sculk-parity' / 'report.json', reports)
assert all(r['pass'] for mode in reports.values() for r in mode.values()), reports
if __name__ == '__main__':
main()
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""Compare the blocks Horizon's structure mods place with the blocks a real server saved.
Expected side: the clean-room structure oracle (see test_structure_layout_parity.py), which kept, for every
start of a mod world, its blocks (`blocks`, the start's box) and every position of the box grown by
`diff_margin` where the mod world differs from the no-mod world of the same seed (`changed_vs_vanilla`).
Horizon side: the chunk_dump probe generates the chunks around each start in full (terrain, structures,
features) twice: from the 26.3 resources (the no-mod world) and from those resources with the mods carried
by `horizon-port-pack carry` (the mod world), as test_structure_layout_parity.py builds them.
The oracle's game is 1.21.1 and Horizon's 26.3, so the worlds also differ where the versions do. A position
is compared only where the two no-mod worlds agree (the oracle's no-mod block is known inside the start's
box and at the changed positions); elsewhere in the grown box, where the oracle saw no change, Horizon's mod
world must equal its no-mod world. Overlapping structures need no special case: both worlds have them.
A mismatch is counted by the oracle's no-mod block, the expected block and Horizon's, so a processor's
missing rule reads as one line. KNOWN names the mismatch classes the implementation does not cover yet, with
the reason; they are reported, not failed.
usage: test_structure_blocks_parity.py [--profile betterdungeons] [--filter REGEX] [--limit N]
"""
import argparse
import gzip
import json
import os
import re
import subprocess
import sys
from collections import Counter, defaultdict
try:
from . import lab, test_structure_layout_parity as layout
except ImportError:
import lab
import test_structure_layout_parity as layout
# profile -> {structure id regex: what the implementation does not cover yet}
KNOWN = {
'betterdungeons': {
r'^betterdungeons:(small|skeleton|zombie)_dungeon$':
"Better Dungeons' placeholder processors and its biome modifier that removes vanilla's "
'monster rooms (spec-betterdungeons §1.2, §3.2) are not implemented yet',
r'^betterdungeons:(spider|small_nether)_dungeon$':
"Better Dungeons' own structure types (spec-betterdungeons §5, §6; OPEN-B14, B15) are not "
'implemented yet',
},
}
def state(text):
"""`name[k=v,...]` with sorted properties, the same for both games' spellings."""
name, _, rest = text.partition('[')
return name + ('[' + ','.join(sorted(rest.rstrip(']').split(','))) + ']' if rest else '')
def state_names(resources):
facts = json.loads((resources / 'facts.json').read_text())
return [state(s[3].removeprefix('Block{').replace('}', '', 1)) for s in facts['states']]
def chunk_rect(box):
x0, _, z0, x1, _, z1 = box
return f'{x0 >> 4},{z0 >> 4},{x1 >> 4},{z1 >> 4}'
def generate(binary, resources, seed, dimension, boxes, names):
"""Block states by position inside `boxes`, from chunk_dump's full generation of their chunks."""
result = subprocess.run([str(binary), 'chunk_dump', str(resources), str(seed), dimension,
*(chunk_rect(b) for b in boxes)], capture_output=True, text=True, cwd=lab.ROOT)
if result.returncode:
raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:])
rows = {} # chunk -> the heights the boxes over it need
for x0, y0, z0, x1, y1, z1 in boxes:
for cx in range(x0 >> 4, (x1 >> 4) + 1):
for cz in range(z0 >> 4, (z1 >> 4) + 1):
low, high = rows.get((cx, cz), (y0, y1))
rows[(cx, cz)] = (min(low, y0), max(high, y1))
blocks, chunk, low, high = {}, None, 0, -1
for line in result.stdout.splitlines():
if line.startswith('chunk '):
_, x, z = line.split()
low, high = rows.get((int(x), int(z)), (0, -1))
chunk = (int(x) * 16, int(z) * 16)
elif line.startswith('y '):
_, y, row = line.split(' ', 2)
y = int(y)
if low <= y <= high:
for i, state_id in enumerate(row.split(' ')):
blocks[(chunk[0] + i % 16, y, chunk[1] + i // 16)] = names[int(state_id)]
return blocks
def oracle_blocks(start):
"""(mod world, no-mod world) block by position: the box in full, the changed positions around it."""
x0, y0, z0, x1, y1, z1 = start['bounding_box']
palette = [state(p) for p in start['blocks']['palette']]
runs = iter(index for index, count in start['blocks']['rle'] for _ in range(count))
mod = {(x, y, z): palette[next(runs)] for y in range(y0, y1 + 1) for z in range(z0, z1 + 1)
for x in range(x0, x1 + 1)}
base = dict(mod)
for x, y, z, mod_state, base_state in start['changed_vs_vanilla']:
mod[(x, y, z)], base[(x, y, z)] = state(mod_state), state(base_state)
return mod, base
def inside(box, p):
return all(box[i] <= p[i] <= box[i + 3] for i in range(3))
def compare(start, vanilla, modded):
"""Compared positions and the mismatches, as (no-mod, expected, Horizon) -> count."""
mod, base = oracle_blocks(start)
compared, mismatches = 0, Counter()
x0, y0, z0, x1, y1, z1 = start['diff_box']
for y in range(y0, y1 + 1):
for z in range(z0, z1 + 1):
for x in range(x0, x1 + 1):
p = (x, y, z)
if p not in vanilla or p not in modded:
continue
if p in base:
if vanilla[p] != base[p]:
continue # the versions differ here
expected = mod[p]
else:
expected = vanilla[p] # the oracle saw no change
compared += 1
if modded[p] != expected:
mismatches[(base.get(p, vanilla[p]), expected, modded[p])] += 1
return compared, mismatches
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--profile', default='betterdungeons', choices=[p for p, v in layout.PROFILES.items() if v['carry']])
parser.add_argument('--filter', default='', help='only structure ids matching this regex')
parser.add_argument('--limit', type=int, default=8, help='mismatch classes shown per structure')
args = parser.parse_args()
profile = layout.PROFILES[args.profile]
results = sorted((layout.ORACLE / args.profile).glob('seed-*.json.gz'))
missing = [jar for jar in profile['mods'].values() if not (layout.JARS / jar).exists()]
if not results or missing:
print(f'SKIP: oracle results or mod jars missing under {layout.ORACLE} (see test_structure_layout_parity.py)')
return 0
resources = layout.overlay(args.profile, layout.carry(args.profile, profile['mods'], profile['carry']))
binary = layout.probe_binary()
names = state_names(lab.RESOURCES)
totals = defaultdict(lambda: [0, 0, Counter()]) # structure -> [starts, compared, mismatches]
for path in results:
oracle = json.load(gzip.open(path))
seed = oracle['seed']
starts = [s for s in oracle['structures'] if s['complete'] and re.search(args.filter, s['id'])]
for dimension in sorted({s['dimension'] for s in starts}):
here = [s for s in starts if s['dimension'] == dimension]
boxes = [s['diff_box'] for s in here]
dim = dimension.removeprefix('minecraft:')
vanilla = generate(binary, lab.RESOURCES, seed, dim, boxes, names)
modded = generate(binary, resources, seed, dim, boxes, names)
for start in here:
compared, mismatches = compare(start, vanilla, modded)
total = totals[start['id']]
total[0] += 1
total[1] += compared
total[2].update(mismatches)
failed = False
for structure, (starts, compared, mismatches) in sorted(totals.items()):
wrong = sum(mismatches.values())
reason = next((r for pattern, r in KNOWN.get(args.profile, {}).items() if re.search(pattern, structure)), None)
verdict = 'ok ' if not wrong else 'known' if reason else 'FAIL '
failed |= verdict == 'FAIL '
print(f'{verdict} {structure}: {starts} starts, {compared - wrong} of {compared} positions match'
+ (f' ({reason})' if wrong and reason else ''))
for (base, expected, got), n in mismatches.most_common(args.limit):
print(f' {n:6} no-mod {base} expected {expected} Horizon {got}')
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())
+101 -51
View File
@@ -17,15 +17,22 @@ The oracle's game is 1.21.1 and Horizon's 26.3. KNOWN lists the starts where 26.
1.21.1, each checked against 26.3 vanilla (VanillaChunkGenerationOracle's `scan`, HORIZON_PIECES=1), whose
pieces equal Horizon's there; they are reported, not failed.
Mod profiles compare the mod world's `pieces` instead. Horizon then reads the mod's own data from its jar
(`.local/structure-oracle/jars/`, or HORIZON_STRUCTURE_JARS): an overlay of the 26.3 resources adds the
jar's structures, sets, pools, processor lists, biome tags and templates, as they are written. The mod's
own processors are left out of the overlay's lists: they change blocks, never which pieces are placed.
Block states are upgraded to 26.3's JSON shape, as the port does.
The jars are the player's; nothing of them enters the repository.
Mod profiles compare the mod world's `pieces` instead, through the path players' packs take: the mod jars
(`.local/structure-oracle/jars/`, or HORIZON_STRUCTURE_JARS) are carried by `horizon-port-pack carry` into
a fresh work folder, and an overlay of the 26.3 resources adds the carried structures, sets, pools,
processor lists, biome tags and templates. The jars are the player's; nothing of them enters the
repository.
usage: test_structure_layout_parity.py [--profile lithostitched|betterdungeons] [--filter REGEX] [--verbose]
The `yung-probe` profiles check YUNG's API's draws with a data pack of the spec team's own (spec-yungsapi
§3, probe experiments e1-e9: fallback, max_count, empty elements, min_required_depth, ignore_bounds,
max_y, is_priority). The pack is carried as one more mod, built at run time from the oracle's profile file
(`.local/structure-oracle/profiles/<profile>.json`), and its starts are read from the oracle's census of
every start (`all_starts`).
usage: test_structure_layout_parity.py [--profile lithostitched|betterdungeons|yung-probe|yung-probe2]
[--filter REGEX] [--verbose]
"""
import base64
import argparse
import gzip
import json
@@ -44,12 +51,16 @@ except ImportError:
ORACLE = Path(os.environ.get('HORIZON_STRUCTURE_ORACLE', lab.LOCAL / 'structure-oracle'))
JARS = Path(os.environ.get('HORIZON_STRUCTURE_JARS', ORACLE / 'jars'))
# Per profile: which saved pieces are expected, the mod jars whose data Horizon reads, and the structures
# compared (a regex; None: every start that has the pieces).
# Per profile: which saved pieces are expected, the mods in the pack (id: jar), those carried, and the
# structures compared (a regex; None: every start that has the pieces).
PROFILES = {
'lithostitched': {'side': 'base_pieces', 'jars': [], 'structures': None},
'betterdungeons': {'side': 'pieces', 'jars': ['YungsApi-1.21.1-NeoForge-5.1.9.jar', 'YungsBetterDungeons-1.21.1-NeoForge-5.1.4.jar'],
'structures': r'^betterdungeons:(small|skeleton|zombie)_dungeon$'},
'lithostitched': {'side': 'base_pieces', 'mods': {}, 'carry': [], 'structures': None},
'betterdungeons': {'side': 'pieces', 'mods': {'yungsapi': 'YungsApi-1.21.1-NeoForge-5.1.9.jar',
'betterdungeons': 'YungsBetterDungeons-1.21.1-NeoForge-5.1.4.jar'},
'carry': ['betterdungeons'], 'structures': r'^betterdungeons:(small|skeleton|zombie)_dungeon$'},
**{name: {'side': 'all_starts', 'mods': {'yungsapi': 'YungsApi-1.21.1-NeoForge-5.1.9.jar'},
'packs': {'probe': name}, 'carry': ['probe'], 'structures': r'^probe:'}
for name in ['yung-probe', 'yung-probe2']},
}
BUNDLES = {'structure': 'structures', 'structure_set': 'structure_sets', 'template_pool': 'template_pools',
'processor_list': 'processor_lists'}
@@ -61,7 +72,7 @@ KNOWN = {
('lithostitched', 1234, 'minecraft:village_plains', -24, 47): 'no start in 26.3 vanilla (nor in Horizon)',
('lithostitched', 1234, 'minecraft:ruined_portal', -16, 51): RUINED_PORTAL,
('lithostitched', 42, 'minecraft:ruined_portal', -19, -38): RUINED_PORTAL,
('betterdungeons', 1234, 'betterdungeons:small_dungeon', 162, 10): SULFUR_CAVES,
('betterdungeons', 1234, 'betterdungeons:small_dungeon', 162, 10): SULFUR_CAVES,
('betterdungeons', 42, 'betterdungeons:small_dungeon', -29, -28): SULFUR_CAVES,
**{('lithostitched', seed, 'minecraft:trial_chambers', x, z): TRIAL_CHAMBERS
for seed, x, z in [(1234, 13, 21), (2, -28, 13), (2, 11, 16), (2, 146, 44), (42, 17, 7), (42, 38, -25)]},
@@ -91,20 +102,49 @@ def expected_piece(saved):
return piece
def upgrade_states(value):
"""1.21.1's block states (`{"Name", "Properties"}`) in 26.3's shape (`{"id", "properties"}`)."""
if isinstance(value, list):
return [upgrade_states(v) for v in value]
if not isinstance(value, dict):
return value
if 'Name' in value and set(value) <= {'Name', 'Properties'}:
return {'id': value['Name'], **({'properties': value['Properties']} if 'Properties' in value else {})}
return {k: upgrade_states(v) for k, v in value.items()}
# horizon-port-pack's jar census (inventory.json); the carry does not read it.
CENSUS = ['blockstates', 'item_models', 'recipes', 'loot_tables', 'tags', 'worldgen', 'structures', 'languages',
'textures', 'sounds', 'classes', 'mixin_configs']
def overlay(profile, jars):
"""The 26.3 resources plus the jars' structure data, in a folder the probe reads as its resources."""
root = lab.LOCAL / 'structure-layout' / profile
def pack_jar(work, mod, profile):
"""The data pack an oracle profile added to its world, as a jar of mod `mod`."""
spec = json.loads((ORACLE / 'profiles' / f'{profile}.json').read_text())
files = {**spec['config_files'], **{path: base64.b64decode(data) for path, data in spec.get('binary_files', {}).items()}}
jar = work / f'{mod}.jar'
with zipfile.ZipFile(jar, 'w') as z:
for path, content in files.items():
parts = Path(path).parts
if parts[:2] == ('world', 'datapacks') and len(parts) > 3:
z.writestr(str(Path(*parts[3:])), content)
return jar
def carry(profile, mods, carried, packs=None):
"""`horizon-port-pack carry` of the profile's mods and packs; the carried mods' data folders."""
work = lab.LOCAL / 'structure-layout' / profile / 'work'
shutil.rmtree(work, ignore_errors=True)
work.mkdir(parents=True)
mods = {key: str(JARS / jar) for key, jar in mods.items()}
mods.update({key: str(pack_jar(work, key, name)) for key, name in (packs or {}).items()})
records = [{'key': key, 'name': key, 'version': '', 'path': jar, 'tier': 'data', 'confidence': 'known',
'class': 'content' if key in carried else 'library', 'source': 'file', 'license': '',
'client': '', 'server': '', 'depends': [], 'layer': 0, 'jar': jar,
'info': {'mod_id': key, 'name': key, 'version': '', 'license': '', 'depends': [],
'census': dict.fromkeys(CENSUS, 0)}}
for key, jar in mods.items()]
(work / 'inventory.json').write_text(json.dumps(records))
subprocess.run(['cargo', 'run', '--release', '-q', '-p', 'horizon-port-pack', '--', 'carry', str(work),
'--resources', str(lab.RESOURCES), *carried], check=True, cwd=lab.ROOT, stdout=subprocess.DEVNULL)
data = [work / 'mods' / key / 'carry' / 'data' for key in carried]
if not all(d.is_dir() for d in data):
raise SystemExit(f'horizon-port-pack carried nothing into {work / "mods"}')
return data
def overlay(profile, data_dirs):
"""The 26.3 resources plus the carried structure data, in a folder the probe reads as its resources."""
root = lab.LOCAL / 'structure-layout' / profile / 'resources'
shutil.rmtree(root, ignore_errors=True)
worldgen = root / 'worldgen'
(worldgen / 'structure').mkdir(parents=True)
@@ -116,28 +156,24 @@ def overlay(profile, jars):
(worldgen / entry.name).symlink_to(entry)
for namespace in (source / 'structure').iterdir():
(worldgen / 'structure' / namespace.name).symlink_to(namespace)
for jar in jars:
with zipfile.ZipFile(JARS / jar) as archive:
for name in archive.namelist():
parts = name.split('/')
if parts[0] != 'data' or len(parts) < 4 or name.endswith('/'):
continue
namespace, kind = parts[1], parts[2]
if kind == 'structure' and name.endswith('.nbt'):
target = worldgen / 'structure' / namespace / '/'.join(parts[3:])
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.read(name))
elif name.endswith('.json') and kind == 'worldgen' and parts[3] in BUNDLES:
value = upgrade_states(json.loads(archive.read(name)))
if parts[3] == 'processor_list':
value['processors'] = [p for p in value['processors'] if p['processor_type'].startswith('minecraft:')]
merged[BUNDLES[parts[3]]][f'{namespace}:' + '/'.join(parts[4:])[:-5]] = json.dumps(value)
elif name.endswith('.json') and parts[2:5] == ['tags', 'worldgen', 'biome']:
tag = f'{namespace}:' + '/'.join(parts[5:])[:-5]
value = json.loads(archive.read(name))
if tag in merged['biome_tags'] and not value.get('replace'):
value['values'] = json.loads(merged['biome_tags'][tag])['values'] + value['values']
merged['biome_tags'][tag] = json.dumps(value)
for data in data_dirs:
for path in sorted(p for p in data.rglob('*') if p.is_file()):
parts = path.relative_to(data).parts
if len(parts) < 3:
continue
namespace, kind = parts[0], parts[1]
if kind == 'structure' and path.suffix == '.nbt':
target = worldgen / 'structure' / namespace / Path(*parts[2:])
target.parent.mkdir(parents=True, exist_ok=True)
target.symlink_to(path)
elif path.suffix == '.json' and kind == 'worldgen' and parts[2] in BUNDLES:
merged[BUNDLES[parts[2]]][f'{namespace}:' + '/'.join(parts[3:])[:-5]] = path.read_text()
elif path.suffix == '.json' and parts[1:4] == ('tags', 'worldgen', 'biome'):
tag = f'{namespace}:' + '/'.join(parts[4:])[:-5]
value = json.loads(path.read_text())
if tag in merged['biome_tags'] and not value.get('replace'):
value['values'] = json.loads(merged['biome_tags'][tag])['values'] + value['values']
merged['biome_tags'][tag] = json.dumps(value)
for name, bundle in merged.items():
(worldgen / f'{name}.json').write_text(json.dumps(bundle))
return root
@@ -179,6 +215,15 @@ def compare(expected, actual):
return None
def census_starts(oracle):
"""The oracle's census of every start (`all_starts`), as `structures` entries with their `all_starts`."""
for chunk in oracle['all_starts']:
for start in chunk['starts']:
if 'children' in start:
yield {'id': start['id'], 'dimension': chunk['dimension'], 'start_chunk': chunk['chunk'],
'all_starts': start['children']}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--profile', default='lithostitched', choices=sorted(PROFILES))
@@ -190,18 +235,23 @@ def main():
print(f'SKIP: no oracle results in {ORACLE / args.profile} (see this file\'s docstring)')
return 0
profile = PROFILES[args.profile]
missing = [jar for jar in profile['jars'] if not (JARS / jar).exists()]
missing = [str(JARS / jar) for jar in profile['mods'].values() if not (JARS / jar).exists()]
missing += [str(ORACLE / 'profiles' / f'{name}.json') for name in profile.get('packs', {}).values()
if not (ORACLE / 'profiles' / f'{name}.json').exists()]
if missing:
print(f'SKIP: mod jars not in {JARS}: {", ".join(missing)}')
print(f'SKIP: not found: {", ".join(missing)}')
return 0
resources = overlay(args.profile, profile['jars']) if profile['jars'] else lab.RESOURCES
resources = lab.RESOURCES
if profile['carry']:
data = carry(args.profile, profile['mods'], profile['carry'], profile.get('packs'))
resources = overlay(args.profile, data)
binary = probe_binary()
matched, known, failed = 0, 0, []
for path in results:
oracle = json.load(gzip.open(path))
seed = oracle['seed']
by_dimension = {}
for start in oracle['structures']:
for start in oracle['structures'] if profile['side'] != 'all_starts' else census_starts(oracle):
if start.get(profile['side']) is None or not re.search(args.filter, start['id']) \
or not re.search(profile['structures'] or '', start['id']):
continue