From d271176f2342e1c2033f4ca38005892c60801f3e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:31:02 +0200 Subject: [PATCH 1/5] Tools and harnesses start the game in scratch folders, not a player's The game logs into HORIZON_HOME and falls back to the player's own game folder when it is unset. Harnesses that set only HORIZON_NO_AUDIO (and test_native_client, which set nothing) wrote logs, and on a world run advancements, into ~/Library/Application Support/horizon. lab.game_env gives every game a fresh HORIZON_HOME, HORIZON_LAUNCHER_HOME, XDG_DATA_HOME and XDG_CONFIG_HOME, no audio and no launcher self-update; a folder the caller passes is kept. Every launcher of the game uses it, parity.py gives each harness its own HORIZON_HOME, and tests/test_game_home.py fails for a script in tools/ that starts the game without it. Co-Authored-By: Claude Sonnet 5.5 --- docs/parity-workflow.md | 4 + tests/test_game_home.py | 102 ++++++++++++++++++++++++++ tools/agent_control_e2e.py | 15 ++-- tools/graphics_bench.py | 7 +- tools/lab.py | 33 +++++++++ tools/lan_e2e.py | 3 +- tools/launcher_mcp_e2e.py | 3 +- tools/mod_browser_harness.py | 8 +- tools/parity.py | 7 ++ tools/perf_bench.py | 2 +- tools/server_bench.py | 2 +- tools/test_block_removal_parity.py | 2 +- tools/test_command_exec_parity.py | 2 +- tools/test_composter_parity.py | 2 +- tools/test_crafter_parity.py | 2 +- tools/test_dedicated_server_parity.py | 4 +- tools/test_dispenser_parity.py | 2 +- tools/test_friends.py | 2 +- tools/test_mace_parity.py | 2 +- tools/test_native_client.py | 2 +- tools/test_online_mode_parity.py | 4 +- tools/test_save_roundtrip_parity.py | 4 +- tools/test_sculk_parity.py | 2 +- tools/test_secure_chat_parity.py | 2 +- tools/test_use_item_on_parity.py | 2 +- tools/test_world_reopen_parity.py | 5 +- tools/test_world_spawn_parity.py | 2 +- 27 files changed, 190 insertions(+), 37 deletions(-) create mode 100644 tests/test_game_home.py diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 1b00080e7..f9f222071 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -32,6 +32,10 @@ Passes are shared between worktrees. A harness's key depends only on the content Every runner on the machine shares `PARITY_MACHINE_JOBS` slots (default: half the CPU threads), so several agents' runs together can't overload it. Parallel harnesses are also admitted by memory: each harness's recorded peak is reserved, within three quarters of the memory available at the start, and a harness starts only if the memory free at that moment still leaves 2 GB. `-j` caps the count here (default: `PARITY_LOCAL_JOBS`, else 3 while other machines help or a third of the CPU threads alone, within `$FLEET_LOAD_JOBS`). +### Harnesses that start the game + +The game logs into `HORIZON_HOME` and falls back to the player's own game folder when it is unset, so a harness that starts the game, `horizon-ctl`, the launcher or the dedicated server builds the environment with `lab.game_env(**extra)`: no audio, and fresh scratch folders for `HORIZON_HOME`, `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and `XDG_CONFIG_HOME`, removed when the harness exits (a folder you pass, or that the environment already has, is kept). The runner also gives each harness its own `HORIZON_HOME` under `.local/parity-runner/game-home/`. `tests/test_game_home.py` fails for a script in `tools/` that starts the game without it. + ### Other machines Harnesses can also run on the Mac mini and the ThinkPad (`tools/parity_hosts.json` describes them; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 3 and only those under 800 MB. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. diff --git a/tests/test_game_home.py b/tests/test_game_home.py new file mode 100644 index 000000000..b4d9e017f --- /dev/null +++ b/tests/test_game_home.py @@ -0,0 +1,102 @@ +"""A tool or harness that starts the game must not write into a real player's folders. + +The game logs into HORIZON_HOME and falls back to the player's own game folder when it is unset, so every +spawn goes through lab.game_env, which sets fresh scratch folders. This test fails for a script in tools/ +that starts the game (or horizon-ctl, the launcher or the dedicated server) without it.""" + +import ast +import os +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import lab + +TOOLS = Path(lab.ROOT) / "tools" + +# Strings that mean "this script starts the game": a binary a harness runs, or the audio switch every game run sets. +SPAWN_MARKERS = { + "HORIZON_NO_AUDIO", "horizon-ctl", "horizon-ctl.exe", "horizon-server", "horizon-server.exe", + "horizon-client.exe", "release/horizon-client", "fast/horizon-client", "debug/horizon-client", +} + +# Scripts that mention those strings without starting a game themselves, and why. +EXEMPT = { + "lab.py": "defines game_env", + "parity.py": "runs the harnesses and gives each its own HORIZON_HOME", + "package_native_client.py": "packs the binaries into an archive", + "build_release.py": "builds and packs the release", + "release_train.py": "release bookkeeping", + "pr_ready.py": "runs cargo checks and parity.py", + "port_harness.py": "ports Java code, starts no game", +} + + +def constants(tree): + """Every string in a script that is a whole literal or a keyword name (docstrings are longer text).""" + for node in ast.walk(tree): + if isinstance(node, ast.Constant) and isinstance(node.value, str): + yield node.value + elif isinstance(node, ast.keyword) and node.arg: + yield node.arg + + +def uses_game_env(tree): + """The script calls lab.game_env, or starts its servers through test_dedicated_server_parity.Server, which does.""" + return any(isinstance(node, ast.Attribute) and node.attr == "game_env" + or isinstance(node, ast.Name) and node.id == "game_env" + or isinstance(node, ast.ImportFrom) and (node.module or "").endswith("test_dedicated_server_parity") + for node in ast.walk(tree)) + + +def sets_audio_by_hand(tree): + return "HORIZON_NO_AUDIO" in set(constants(tree)) + + +class GameEnvTests(unittest.TestCase): + def test_gives_every_game_scratch_folders(self): + with mock.patch.dict(os.environ, {}, clear=False): + for key in ("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"): + os.environ.pop(key, None) + first, second = lab.game_env(), lab.game_env() + self.assertEqual(first["HORIZON_NO_AUDIO"], "1") + self.assertEqual(first["HORIZON_LAUNCHER_NO_SELF_UPDATE"], "1") + for key in ("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"): + self.assertTrue(Path(first[key]).is_dir(), key) + self.assertNotEqual(first[key], second[key], key) + + def test_keeps_the_callers_folders(self): + with tempfile.TemporaryDirectory() as temp: + env = lab.game_env({"PATH": "x", "HORIZON_HOME": "/from/base"}, HORIZON_LAUNCHER_HOME=Path(temp), A=1) + self.assertEqual(env["HORIZON_HOME"], "/from/base") + self.assertEqual(env["HORIZON_LAUNCHER_HOME"], temp) + self.assertEqual((env["PATH"], env["A"]), ("x", "1")) + + def test_does_not_touch_the_process_environment(self): + before = dict(os.environ) + lab.game_env() + self.assertEqual(dict(os.environ), before) + + +class SpawnerTests(unittest.TestCase): + def test_every_script_that_starts_the_game_uses_game_env(self): + offenders = [] + for path in sorted(TOOLS.rglob("*.py")): + if path.name in EXEMPT: + continue + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + if SPAWN_MARKERS & set(constants(tree)) and not uses_game_env(tree): + offenders.append(str(path.relative_to(lab.ROOT))) + self.assertEqual(offenders, [], "these start the game without lab.game_env (HORIZON_HOME falls back to a " + "real player's folder); use it, or list the script in EXEMPT") + + def test_nobody_sets_the_audio_switch_by_hand(self): + offenders = [str(path.relative_to(lab.ROOT)) for path in sorted(TOOLS.rglob("*.py")) + if path.name not in EXEMPT + and sets_audio_by_hand(ast.parse(path.read_text(encoding="utf-8"), filename=str(path)))] + self.assertEqual(offenders, [], "set it through lab.game_env, which also gives the game scratch folders") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 3fcf39553..7f0c52bce 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -67,17 +67,20 @@ class Failed(Exception): pass -def game_env(screen): +def game_env(screen, home=None): + """The environment of a game: lab.game_env with HORIZON_HOME `home` (a scratch folder when None), no live-count + ping, and on Linux the virtual screen `screen`.""" + extra = {'HORIZON_TELEMETRY_URL': 'off'} # no live-count ping from test games + if home is not None: + extra['HORIZON_HOME'] = home if sys.platform == 'darwin': - return dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off') - env = dict(os.environ, VSCREEN=screen) + return lab.game_env(**extra) + env = lab.game_env(VSCREEN=screen, **extra) subprocess.run(['vscreen', 'up'], env=env, check=False, capture_output=True) text = subprocess.run(['vscreen', 'env'], env=env, capture_output=True, text=True, check=True).stdout env.pop('DISPLAY', None) for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]): env[match.group(1)] = match.group(2) - env['HORIZON_NO_AUDIO'] = '1' - env['HORIZON_TELEMETRY_URL'] = 'off' # no live-count ping from test games if LAVAPIPE.exists(): env['VK_ICD_FILENAMES'] = str(LAVAPIPE) return env @@ -632,7 +635,7 @@ def scratch(mode, resources): (work / '.local/horizon-client').mkdir() os.symlink(resources, work / '.local/horizon-client' / lab.VERSION) # horizon-ctl reads No AI in the game home: this one, not the player's. - env = dict(game_env(os.environ.get('VSCREEN', 'agent-control')), HORIZON_HOME=str(work)) + env = game_env(os.environ.get('VSCREEN', 'agent-control'), home=work) return work, env diff --git a/tools/graphics_bench.py b/tools/graphics_bench.py index 0e42e94d5..f19165f62 100644 --- a/tools/graphics_bench.py +++ b/tools/graphics_bench.py @@ -53,15 +53,14 @@ guiScale:0 def vscreen_env(): out = subprocess.run(["vscreen", "env"], cwd=ROOT, capture_output=True, text=True, check=True) - env = dict(os.environ) + env = lab.game_env() for part in out.stdout.replace(";", " ").split(): if "=" in part and not part.startswith("export"): k, v = part.split("=", 1) env[k] = v env.pop("DISPLAY", None) - # Benchmark games never play sound on the machine's speakers. - env["HORIZON_NO_AUDIO"] = "1" - # Nor reach the telemetry server (docs/telemetry.md). + # lab.game_env: no sound on the machine's speakers, and scratch folders instead of the player's. + # Benchmark games do not reach the telemetry server (docs/telemetry.md). env["HORIZON_TELEMETRY_URL"] = "off" return env diff --git a/tools/lab.py b/tools/lab.py index a62a38f59..b7cc2f795 100644 --- a/tools/lab.py +++ b/tools/lab.py @@ -5,6 +5,7 @@ generated files stay in .local/. Also the small helpers the harnesses share (free ports, offline UUIDs, VarInts, float bits).""" import argparse +import atexit from collections import Counter import hashlib import json @@ -54,6 +55,38 @@ def cargo_target(): return ROOT / os.environ.get("CARGO_TARGET_DIR", "target") +_SCRATCH_DIRS = [] + + +def _scratch_dir(prefix): + path = tempfile.mkdtemp(prefix=prefix) + _SCRATCH_DIRS.append(path) + return path + + +@atexit.register +def _remove_scratch_dirs(): + for path in _SCRATCH_DIRS: + shutil.rmtree(path, ignore_errors=True) + + +def game_env(base=None, **extra): + """The environment for every run of the game, the launcher or horizon-ctl from a tool or a harness: no audio, + and fresh scratch folders for the game's home (logs, saves, options), the launcher's home and the XDG folders, + so a run never writes into a real player's folders (the game falls back to them when HORIZON_HOME is unset). + A folder the caller already has in `base` (default os.environ) or passes in `extra` is kept. The scratch folders + are removed when this process exits.""" + env = dict(os.environ if base is None else base) + env.update({key: str(value) for key, value in extra.items()}) + env["HORIZON_NO_AUDIO"] = "1" + env["HORIZON_LAUNCHER_NO_SELF_UPDATE"] = "1" + for key, prefix in (("HORIZON_HOME", "horizon-home-"), ("HORIZON_LAUNCHER_HOME", "horizon-launcher-home-"), + ("XDG_DATA_HOME", "horizon-xdg-data-"), ("XDG_CONFIG_HOME", "horizon-xdg-config-")): + if not env.get(key): + env[key] = _scratch_dir(prefix) + return env + + def write_json(path, data): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 3ece4b448..9d0586a2c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -275,8 +275,7 @@ class Game: (self.work / '.local/horizon-client').mkdir(parents=True) os.symlink(resources, self.work / '.local/horizon-client' / lab.VERSION) self.socket = self.work / 'c.sock' - env = game_env(os.environ.get('VSCREEN', 'lan-e2e')) - env['HORIZON_HOME'] = str(self.work / 'home') + env = game_env(os.environ.get('VSCREEN', 'lan-e2e'), home=self.work / 'home') self.d = Cli(ctl, self.socket, self.work, env) self.d.name = name diff --git a/tools/launcher_mcp_e2e.py b/tools/launcher_mcp_e2e.py index 0b827d288..748acafc2 100644 --- a/tools/launcher_mcp_e2e.py +++ b/tools/launcher_mcp_e2e.py @@ -167,8 +167,7 @@ def main(): os.symlink(bins / name, version / name) os.symlink(resources, version / '.local/horizon-client' / lab.VERSION) (version / '.installed').write_text('') - env = dict(os.environ, HORIZON_LAUNCHER_HOME=str(work / 'launcher'), HORIZON_HOME=str(work / 'home'), - HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off') + env = lab.game_env(HORIZON_LAUNCHER_HOME=work / 'launcher', HORIZON_HOME=work / 'home', HORIZON_TELEMETRY_URL='off') m = Mcp(Path(args.launcher).resolve(), env) try: summary = scenario(m, out) diff --git a/tools/mod_browser_harness.py b/tools/mod_browser_harness.py index 4531570bc..cf33d85de 100755 --- a/tools/mod_browser_harness.py +++ b/tools/mod_browser_harness.py @@ -33,6 +33,11 @@ import tempfile import time from pathlib import Path +try: + from . import lab +except ImportError: + import lab + ROOT = Path(__file__).resolve().parents[1] @@ -154,8 +159,7 @@ def main(): args = ap.parse_args() home = Path(tempfile.mkdtemp(prefix="horizon-mod-browser-")) - env = dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO="1", HORIZON_NO_HEARTBEAT="1", - HORIZON_CONTROL=str(home / "ctl.sock")) + env = lab.game_env(HORIZON_HOME=home, HORIZON_NO_HEARTBEAT="1", HORIZON_CONTROL=home / "ctl.sock") launcher = [args.launcher] game = Game(str(Path(args.bin) / "horizon-ctl"), str(Path(args.bin) / "horizon-client"), args.resources, home, env) diff --git a/tools/parity.py b/tools/parity.py index 4ed75f5ef..38a2fcde6 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -39,6 +39,7 @@ import json import os from pathlib import Path, PurePosixPath import re +import shutil import socket import subprocess import sys @@ -809,6 +810,12 @@ class LocalExecutor: trace.unlink(missing_ok=True) log = (STATE_DIR / "logs" / f"{name}.log").open("w") environment = run_environment(reuse) + # A game the harness starts logs into HORIZON_HOME, which is a real player's folder when it is unset + # (lab.game_env keeps this one). + game_home = STATE_DIR / "game-home" / name + shutil.rmtree(game_home, ignore_errors=True) + game_home.mkdir(parents=True) + environment.setdefault("HORIZON_HOME", str(game_home)) environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True)) environment.pop("PARITY_SHARD", None) if shard: diff --git a/tools/perf_bench.py b/tools/perf_bench.py index 31024737c..5f5f57305 100644 --- a/tools/perf_bench.py +++ b/tools/perf_bench.py @@ -400,7 +400,7 @@ def run_horizon(args, distance): for carry in dev_mods(args): command += ["--dev-mod", str(carry)] # Benchmark runs stay out of the live count and send nothing (docs/telemetry.md). - env = dict(os.environ, HORIZON_NO_AUDIO="1", HORIZON_TELEMETRY_URL="off") + env = lab.game_env(HORIZON_TELEMETRY_URL="off") if args.warm: # A first start to the title screen builds what later starts reuse (the content-mod # root, the block behaviour snapshot). It is not measured: players see it once. diff --git a/tools/server_bench.py b/tools/server_bench.py index a9a494efd..bf1cdabeb 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -120,7 +120,7 @@ class Server: self.process = subprocess.Popen([str(c) for c in command], cwd=directory, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding='utf-8', errors='replace', - env=dict(os.environ, HORIZON_NO_AUDIO='1')) + env=lab.game_env()) threading.Thread(target=self._read, daemon=True).start() def _read(self): diff --git a/tools/test_block_removal_parity.py b/tools/test_block_removal_parity.py index 6ebbbf1d3..3185bd4bb 100755 --- a/tools/test_block_removal_parity.py +++ b/tools/test_block_removal_parity.py @@ -183,7 +183,7 @@ def main(): d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, - env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) # Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared. ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/test_command_exec_parity.py b/tools/test_command_exec_parity.py index 9d57d3f69..877bd0b38 100644 --- a/tools/test_command_exec_parity.py +++ b/tools/test_command_exec_parity.py @@ -82,7 +82,7 @@ def main(): rust_dir = build / 'rust' shutil.rmtree(rust_dir, ignore_errors=True) rust_dir.mkdir() - env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl')) + env = lab.game_env(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')] diff --git a/tools/test_composter_parity.py b/tools/test_composter_parity.py index e632527ce..074b227a8 100644 --- a/tools/test_composter_parity.py +++ b/tools/test_composter_parity.py @@ -125,7 +125,7 @@ def main(): d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, - env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) rust = h.split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/test_crafter_parity.py b/tools/test_crafter_parity.py index 1b9564f41..b9c343d4d 100644 --- a/tools/test_crafter_parity.py +++ b/tools/test_crafter_parity.py @@ -245,7 +245,7 @@ def main(): d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, - env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) rust = h.split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index f45df9822..6a6d258d4 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -126,7 +126,7 @@ class Server: self.lines = [] self.process = subprocess.Popen(list(map(str, command)), cwd=directory, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, - encoding='utf-8', errors='replace') + encoding='utf-8', errors='replace', env=lab.game_env()) self.reader = threading.Thread(target=self._read, daemon=True) self.reader.start() @@ -352,7 +352,7 @@ def horizon_client_joins(vanilla_server, binary, world, build, reference): server = Server(vanilla_server, directory, label) try: server.wait_for(r'Done \(') - env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report)) + env = lab.game_env(HORIZON_NET_REPORT=report) with (build / 'horizon-client-run.log').open('w') as log: subprocess.run([str(c) for c in [binary, '--resources', lab.RESOURCES, '--render-distance', 2, '--server', f'127.0.0.1:{port}', '--name', PLAYER]], diff --git a/tools/test_dispenser_parity.py b/tools/test_dispenser_parity.py index 844322aeb..a6d1f429a 100644 --- a/tools/test_dispenser_parity.py +++ b/tools/test_dispenser_parity.py @@ -417,7 +417,7 @@ def main(): run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, - env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) # Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared. ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) diff --git a/tools/test_friends.py b/tools/test_friends.py index 8fa1a4fee..cc5d15b92 100644 --- a/tools/test_friends.py +++ b/tools/test_friends.py @@ -96,7 +96,7 @@ class Game: self.process = subprocess.Popen(Game.prefix + [ str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain', '--control-socket', str(self.endpoint), '--timeout-seconds', '600', - ] + Game.extra, cwd=self.home, env=dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_NO_AUDIO='1', **env), + ] + Game.extra, cwd=self.home, env=lab.game_env(HORIZON_HOME=self.home, **env), stdout=self.log, stderr=subprocess.STDOUT) wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title') diff --git a/tools/test_mace_parity.py b/tools/test_mace_parity.py index 123f19693..578e9e6ee 100644 --- a/tools/test_mace_parity.py +++ b/tools/test_mace_parity.py @@ -170,7 +170,7 @@ def main(): d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, - env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) rust = h.split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/test_native_client.py b/tools/test_native_client.py index 73e6f3223..552ea8c42 100644 --- a/tools/test_native_client.py +++ b/tools/test_native_client.py @@ -71,7 +71,7 @@ def main(): str(executable), '--radius', '1', '--frames', '30', '--smoke-report', str(report), '--timeout-seconds', '60'] with (root / 'startup-smoke.log').open('w') as log: - subprocess.run(command, cwd=lab.ROOT, env=environment, check=True, + subprocess.run(command, cwd=lab.ROOT, env=lab.game_env(environment), check=True, stdout=log, stderr=subprocess.STDOUT, timeout=120) result = json.loads(report.read_text()) if (result.get('error') is not None or result.get('presented_frames') != 30 diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py index d430c2a68..d03838bf3 100644 --- a/tools/test_online_mode_parity.py +++ b/tools/test_online_mode_parity.py @@ -179,7 +179,7 @@ def run_client(binary, build, port, label, token, discovery): shutil.rmtree(directory, ignore_errors=True) directory.mkdir() report = directory / 'report.json' - env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report), HORIZON_API_DISCOVERY=discovery) + env = lab.game_env(HORIZON_NET_REPORT=report, HORIZON_API_DISCOVERY=discovery) command = [binary, '--resources', lab.RESOURCES, '--render-distance', 2, '--server', f'127.0.0.1:{port}', '--name', PLAYER] if token: @@ -246,7 +246,7 @@ def run_side(label, command, binary, build, services, discovery): 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') - os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery) + os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery)) server = Server(command, directory, f'{label}-online') checks = [] starts = [] diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index bd8b07a29..732429881 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -330,7 +330,7 @@ def entity_uuid_text(i): def vscreen_env(): text = subprocess.run(['vscreen', 'env'], capture_output=True, text=True, check=True).stdout - env = dict(os.environ) + env = lab.game_env() env.pop('DISPLAY', None) for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]): env[match.group(1)] = match.group(2) @@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir): ctl = [str(bin_dir / 'horizon-ctl'), '--socket', str(socket)] extra = [] if sys.platform == 'darwin': - env = dict(os.environ, HORIZON_NO_AUDIO='1') + env = lab.game_env() extra = ['--offscreen'] else: alsa = destination / 'null-asound.conf' diff --git a/tools/test_sculk_parity.py b/tools/test_sculk_parity.py index b9c7417a5..ae2c1c6aa 100644 --- a/tools/test_sculk_parity.py +++ b/tools/test_sculk_parity.py @@ -339,7 +339,7 @@ def main(): oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, 'compile-rust') oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon', - env={**os.environ, 'HORIZON_SCULK_FIXTURE': f'{inputs},{build / "horizon.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_SCULK_FIXTURE=f'{inputs},{build / "horizon.txt"}')) if args.java_only: return names = {s[0] for _, s in chosen} diff --git a/tools/test_secure_chat_parity.py b/tools/test_secure_chat_parity.py index c6c76a892..b9062568a 100644 --- a/tools/test_secure_chat_parity.py +++ b/tools/test_secure_chat_parity.py @@ -264,7 +264,7 @@ def main(): oh.run_logged([*java, 'keys', build], build, 'keys') services = Services(json.loads((build / 'publickeys.json').read_text())) discovery = services.url + '/minecraft/client' - os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery) + os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery)) servers = { 'vanilla': ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'], diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index d6e5f899f..89b463116 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -375,7 +375,7 @@ def main(): d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, - env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}')) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) native = h.split_cases((work / 'native.txt').read_text(), ignore) rust = h.split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/test_world_reopen_parity.py b/tools/test_world_reopen_parity.py index 381927013..4ef9a5e87 100644 --- a/tools/test_world_reopen_parity.py +++ b/tools/test_world_reopen_parity.py @@ -24,6 +24,9 @@ import sys import tempfile from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import lab # noqa: E402 + ROOT = Path(__file__).resolve().parent.parent RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3' RUN = ROOT / '.local' / 'world-reopen' @@ -32,7 +35,7 @@ CYCLES = 3 def game_env(): """macOS renders offscreen; Linux uses the virtual screen (as test_save_roundtrip_parity).""" - env = dict(os.environ, HORIZON_NO_AUDIO='1') + env = lab.game_env() if sys.platform == 'darwin': return env, ['--offscreen'] subprocess.run(['vscreen', 'up'], check=False, capture_output=True) diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 5daa38a45..00c390005 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -140,7 +140,7 @@ def main(): # One worker thread: the chunks decorated in a fixed order (see above). vanilla_server = ['java', '-Xmx2g', '-Dmax.bg.threads=1', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui'] - os.environ['HORIZON_NO_AUDIO'] = '1' + os.environ.update(lab.game_env()) def one(seed): t0 = time.time() From 7c27b85fbd290a48ff000dfcb3e84f862914752a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:08:31 +0200 Subject: [PATCH 2/5] server_pack_e2e: start the game and the servers through lab.game_env The new home-leak test rejects scripts that set HORIZON_NO_AUDIO by hand; this one, added on main since, did. Co-Authored-By: Claude Opus 5.5 --- tools/server_pack_e2e.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tools/server_pack_e2e.py b/tools/server_pack_e2e.py index 83e434435..160083d5e 100644 --- a/tools/server_pack_e2e.py +++ b/tools/server_pack_e2e.py @@ -206,9 +206,8 @@ class Game: self.home = work / 'home' for d in ('home', 'launcher', 'data', 'config'): (work / d).mkdir(parents=True) - self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'), - XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'), - HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off') + self.env = lab.game_env(HORIZON_HOME=self.home, HORIZON_LAUNCHER_HOME=work / 'launcher', + XDG_DATA_HOME=work / 'data', XDG_CONFIG_HOME=work / 'config', HORIZON_TELEMETRY_URL='off') self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')] self.log = work / 'c.log' reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources) @@ -343,7 +342,7 @@ class Run: ('XDG_CONFIG_HOME', 'config')): (work / 'servers' / sub).mkdir(parents=True) os.environ[var] = str(work / 'servers' / sub) - os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off') + os.environ.update(lab.game_env(HORIZON_TELEMETRY_URL='off')) game = self.game = Game(Path(self.args.bin), self.resources, work / 'game') servers_dat = game.home / 'servers.dat' downloads = game.home / 'downloads' From fe253fe534c7dc45e371d8f2c4508e25826da898 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:44:59 +0200 Subject: [PATCH 3/5] Server clients: dropped items and falling blocks fall by themselves between updates A server sends an item's and a falling block's position only every 20 ticks. As a client (multiplayer, a LAN guest, single player on its server thread) Horizon moved them only when a position arrived, three steps towards it, so a dropped item or falling sand hung in the air and then jumped down once a second (#1568). Vanilla runs ItemEntity.tick and FallingBlockEntity.tick on the client too (gravity, collisions, drag), takes their motion from AddEntity (recreateFromPacket) and SetEntityMotion (Entity.lerpMotion), and snaps them to each position packet: neither overrides Entity's NO_OP InterpolationHandler. The client now does the same, with the same ticks single player in-frame uses; only the server removes them or places the block. lan_e2e --check falling: the guest samples both every 2 ticks over 16 ticks. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 72 +++++++++++++------ .../src/game/remote_projectiles.rs | 16 +++-- tools/lan_e2e.py | 44 ++++++++++++ 3 files changed, 106 insertions(+), 26 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 45ba4bebe..1c7e30abb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -140,8 +140,9 @@ pub(super) struct Remote { stepped: HashMap, /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. head_lerps: HashMap, - /// Item entities waiting for their item data. - pending_items: HashMap, + /// Item entities waiting for their item data: where they are and their + /// motion. + pending_items: HashMap, health: (f32, i32, f32), game_mode: i32, pub chat: Vec<(String, Instant)>, @@ -1382,7 +1383,7 @@ impl Game<'_> { } if let Some(r) = self.remote.as_mut() { if kind == "minecraft:item" { - r.pending_items.insert(id, position); + r.pending_items.insert(id, (position, Vec3::ZERO)); } r.entities.insert( id, @@ -1461,6 +1462,23 @@ impl Game<'_> { m.on_ground = on_ground; return; } + if let Some(p) = r.pending_items.get_mut(&id) { + p.0 = position; + } + // ItemEntity and FallingBlockEntity keep Entity's NO_OP + // InterpolationHandler: moveOrInterpolateTo puts them there at + // once, and their own tick moves them on between the server's + // updates (`tick_remote_entities`). + let at = Vec3::new(position[0], position[1], position[2]); + if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + d.position = at; + d.on_ground = on_ground; + return; + } + if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) { + f.position = at; + return; + } // AbstractInterpolationHandler.interpolateTo: without a rotation, // the one it was heading for. let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation)); @@ -1472,9 +1490,6 @@ impl Game<'_> { steps: 3, }, ); - if let Some(p) = r.pending_items.get_mut(&id) { - *p = position; - } } self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground); self.turn_remote_projectile(id, rotation); @@ -1807,6 +1822,8 @@ impl Game<'_> { } } self.spawn_entity(p.id, &kind, p.position, rotation); + // Entity.recreateFromPacket: setDeltaMovement(packet.getMovement()). + self.remote_motion(p.id, p.velocity); if !self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data) { self.spawn_remote_projectile( p.id, @@ -2125,6 +2142,8 @@ impl Game<'_> { pl.velocity = Vec3::new(p.velocity[0], p.velocity[1], p.velocity[2]); } } + // The same packet for another entity: Entity.lerpMotion. + C::SetEntityMotion(p) => self.remote_motion(p.id, p.velocity), // ClientPacketListener.handleDamageEvent: LivingEntity.handleDamageEvent // jolts the walk animation and restarts the hurt flash. Its hurt // sound comes as a sound from Horizon's host, which plays it itself. @@ -2933,7 +2952,9 @@ impl Game<'_> { item.stack = stack; return; } - let Some(p) = position else { return }; + let Some((p, velocity)) = position else { + return; + }; let at = Vec3::new(p[0], p[1], p[2]); let bob_offset = self.world.random.next_float() * std::f32::consts::PI * 2.0; self.dropped.push(ItemEntity { @@ -2944,7 +2965,7 @@ impl Game<'_> { stack, position: at, previous: at, - velocity: Vec3::ZERO, + velocity, on_ground: false, age: 0, pickup_delay: 0, @@ -2952,6 +2973,23 @@ impl Game<'_> { ticks: 0, }); } + /// `Entity.lerpMotion` (and `recreateFromPacket`'s motion) for the + /// entities whose own tick moves them on a client: dropped items and + /// falling blocks. + fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) { + let v = Vec3::new(velocity[0], velocity[1], velocity[2]); + if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + d.velocity = v; + } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) { + f.velocity = v; + } else if let Some(p) = self + .remote + .as_mut() + .and_then(|r| r.pending_items.get_mut(&id)) + { + p.1 = v; + } + } fn apply_remote_health(&mut self) { let Some((health, food, saturation)) = self.remote.as_ref().map(|r| r.health) else { return; @@ -3471,20 +3509,12 @@ impl Game<'_> { l.steps -= 1; } } + // ItemEntity.tick runs on a client too: gravity, collisions and + // friction move the item between the server's updates (every 20 + // ticks), and only the server removes it. + let (world, facts, collision) = (&self.world, self.res.facts(), self.collision); for d in self.dropped.iter_mut().filter(|_| running) { - d.previous = d.position; - d.age += 1; - if let Some(l) = lerps.get_mut(&(d.id as i32)) - && l.steps > 0 - { - let n = f64::from(l.steps); - d.position = Vec3::new( - d.position.x + (l.target[0] - d.position.x) / n, - d.position.y + (l.target[1] - d.position.y) / n, - d.position.z + (l.target[2] - d.position.z) / n, - ); - l.steps -= 1; - } + d.tick(world, facts, collision, false); } head_lerps.retain(|_, (_, steps)| *steps > 0); for (item, ticks, at, eye, pitch, yaw) in using { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 58f82e3a9..33c69728b 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -2,7 +2,7 @@ //! end crystals on a server's client (`ClientPacketListener.handleAddEntity` //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. -use super::{FallingBlock, Game}; +use super::{FallStep, FallingBlock, Game}; use horizon_client::projectiles::{Projectile, ProjectileKind}; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_protocol::entity_data::Value; @@ -185,11 +185,17 @@ impl Game<'_> { t.previous = t.position; t.position = step(t.id, t.position); } - for f in &mut self.falling { - f.previous = f.position; - f.age += 1; - f.position = step(f.id, f.position); + // FallingBlockEntity.tick runs on a client too: the block falls by + // itself between the server's updates (every 20 ticks), then waits + // where it lands for the server to place it and remove it. + let mut falling = std::mem::take(&mut self.falling); + for f in &mut falling { + if let Ok(FallStep::Landed(_)) = self.fall_step(f, false) { + // Block.updateEntityMovementAfterFallOn, then the air drag. + f.velocity = Vec3::new(f.velocity.x * 0.98, 0.0, f.velocity.z * 0.98); + } } + self.falling = falling; for p in &mut self.creatures.projectiles { p.previous = p.position; p.age += 1; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 3ece4b448..a0fe0e181 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -228,6 +228,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - villagers: the guest sees each villager's and zombie villager's type, profession and level as the host has them, and an unemployed villager that takes a composter becomes a farmer on the guest too (the guest used to draw every villager as an unemployed plains one). +- 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). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -5496,5 +5499,46 @@ CHECKS += ['villagers'] CHECK_FNS.update(villagers=check_villagers) +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.""" + x, y, z = (int(v // 1) for v in pos_of(guest)) + top = y + 30 + tag = 'falling_e2e' + host('command', command=f'fill {x + 2} {y} {z - 1} {x + 4} {top + 2} {z + 1} minecraft:air') + host('command', command=f'summon minecraft:item {x + 3.5} {top} {z + 0.5} ' + 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': []} + try: + for _ in range(8): + items = [e['pos'][1] for e in guest.raw('entities', 48, 'minecraft:item')['entities'] + if abs(e['pos'][0] - x - 3.5) < 0.5 and abs(e['pos'][2] - z - 0.5) < 0.5] + 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] + heights['item'].append(items[0] if items else None) + heights['falling block'].append(blocks[0] if blocks else None) + guest.wait(2) + guest.shot(out, 'falling') + finally: + host('command', command=f'kill @e[tag={tag}]') + host('command', command=f'fill {x + 2} {y} {z - 1} {x + 4} {top + 2} {z + 1} minecraft:air') + for name, ys in heights.items(): + seen = [h for h in ys if h is not None] + assert len(seen) >= 6, f'the guest saw the {name} {len(seen)} times of 8: {heights}' + 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 + + +CHECKS += ['falling'] +CHECK_FNS.update(falling=check_falling) + + if __name__ == '__main__': main() From 87f377b29cc885757c95d71e2e65bc0454bf8898 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 03:24:05 +0100 Subject: [PATCH 4/5] launcher: remove a version on a background thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clicking Remove deleted the version's thousands of files on the UI thread, so the whole launcher froze for seconds (more on Windows). The removal now runs on a thread and ends with Msg::Removed. The version leaves the installed list at once (nothing can launch, select or prepare it) and its row shows "Removing…" with a moving bar; installing it again is refused until it is gone. Co-Authored-By: Claude Sonnet 5.5 --- launcher/src/backend.rs | 2 ++ launcher/src/main.rs | 76 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 69 insertions(+), 9 deletions(-) diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index d12dcd13c..efdfa2415 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -2170,6 +2170,8 @@ pub enum Msg { Links(Links), Progress(String, f32), Installed(String, Result<(), String>), + /// A version's files are gone (or could not be deleted). + Removed(String, Result<(), String>), Line(Job, String), Exit(Job, Result<(), String>), Updates(Result), diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 4a68ecdef..0bcbc4011 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -144,6 +144,9 @@ struct Launcher { releases: Load>, installed: Vec, installing: Option<(String, f32)>, + /// The version being deleted on a background thread. It is already out of `installed`, so + /// nothing can launch, select or prepare it, and its row can't install or remove it again. + removing: Option, install_error: Option<(String, String)>, confirm_remove: Option, picker_open: bool, @@ -286,6 +289,7 @@ impl Launcher { releases: Load::Loading, installed, installing: None, + removing: None, install_error: None, confirm_remove: None, picker_open: false, @@ -415,7 +419,7 @@ impl Launcher { let Some(release) = self.updates.horizon.clone() else { return; }; - if self.installing.is_some() { + if self.installing.is_some() || self.removing.as_ref() == Some(&release.tag) { return; } let select = @@ -542,6 +546,17 @@ impl Launcher { Err(e) => self.install_error = Some((tag, e)), } } + Msg::Removed(tag, result) => { + if self.removing.as_ref() == Some(&tag) { + self.removing = None; + } + self.installed = backend::installed(); + self.settings.selected = + selection_after_removal(&self.installed, Settings::load().selected); + if let Err(e) = result { + self.install_error = Some((tag, e)); + } + } Msg::Updates(Ok(updates)) => { self.update_error = None; self.updates = updates; @@ -706,7 +721,7 @@ impl Launcher { } fn install(&mut self, release: &Release) { - if release.asset.is_none() { + if release.asset.is_none() || self.removing.as_ref() == Some(&release.tag) { return; } let (release, tx) = (release.clone(), self.tx.clone()); @@ -724,15 +739,26 @@ impl Launcher { }); } + /// Deletes an installed version on a background thread: a version is thousands of files and + /// the window must keep drawing meanwhile. `Msg::Removed` ends it. fn remove(&mut self, tag: &str) { - if let Err(e) = backend::remove_version(tag) { - self.install_error = Some((tag.to_string(), e)); - } self.confirm_remove = None; - self.installed = backend::installed(); - self.settings.selected = Settings::load() - .selected - .or_else(|| self.installed.first().cloned()); + if self.removing.is_some() + || self.installing.as_ref().is_some_and(|(t, _)| t == tag) + || !self.installed.iter().any(|t| t == tag) + { + return; + } + self.install_error = None; + self.removing = Some(tag.to_string()); + self.installed.retain(|t| t != tag); + self.settings.selected = + selection_after_removal(&self.installed, self.settings.selected.take()); + let (tag, tx) = (tag.to_string(), self.tx.clone()); + std::thread::spawn(move || { + let result = backend::remove_version(&tag); + let _ = tx.send(Msg::Removed(tag, result)); + }); } fn prepare(&mut self) { @@ -1158,6 +1184,14 @@ fn segments( })) } +/// The selected version once one has been removed: the saved choice if it is still installed, +/// else the newest left. +fn selection_after_removal(installed: &[String], saved: Option) -> Option { + saved + .filter(|s| installed.contains(s)) + .or_else(|| installed.first().cloned()) +} + fn disabled(b: Stateful
) -> Stateful
{ b.opacity(theme::DISABLED).cursor_default().tab_stop(false) } @@ -2923,6 +2957,7 @@ impl Launcher { self.installing.as_ref().is_some_and(|(t, _)| t == tag) || self.install_error.as_ref().is_some_and(|(t, _)| t == tag) || self.confirm_remove.as_ref() == Some(tag) + || self.removing.as_ref() == Some(tag) }; let list = self.long_list.clone().column( &self.content_scroll.handle, @@ -2959,6 +2994,15 @@ impl Launcher { .child(format!("{:.0}%", p * 100.)), ) .into_any_element() + } else if self.removing.as_ref() == Some(&tag) { + div() + .flex() + .items_center() + .gap(px(10.)) + .w(px(180.)) + .child(progress_bar(None, &t)) + .child(text(theme::MICRO).text_color(t.muted).child("Removing…")) + .into_any_element() } else if installed { let confirming = self.confirm_remove.as_ref() == Some(&tag); let (t1, t2) = (tag.clone(), tag.clone()); @@ -3587,6 +3631,20 @@ mod tests { assert!(hit.iter().any(|b| b.action().partial_eq(&CloseWindow))); } + #[test] + fn the_selection_survives_a_removal_or_moves_to_the_newest_left() { + let left = ["v0.2.49".to_string(), "v0.2.48".to_string()]; + let pick = + |saved: Option<&str>| super::selection_after_removal(&left, saved.map(String::from)); + assert_eq!(pick(Some("v0.2.48")).as_deref(), Some("v0.2.48")); + assert_eq!(pick(Some("v0.2.47")).as_deref(), Some("v0.2.49")); + assert_eq!(pick(None).as_deref(), Some("v0.2.49")); + assert_eq!( + super::selection_after_removal(&[], Some("v0.2.47".into())), + None + ); + } + #[test] fn the_app_menu_has_quit() { let menus = super::menus(); From 486df91b2db998fb012a088a3c4b0d3d2146ebdb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 05:35:36 +0100 Subject: [PATCH 5/5] refactor(port-pack): move YUNG, Lithostitched and CTOV conversion into legacy_structure_mods A pure move, no behaviour change. The conversion of YUNG's API and its mods, Lithostitched and ChoiceTheorem's Overhauled Village was mixed with the general conversion code in worldgen.rs and processors.rs. It now lives in crates/horizon-port-pack/src/legacy_structure_mods/{yung,lithostitched,ctov}.rs, and the general code reaches it through a few entry points, so a clean-room rewrite can replace the module without touching the rest. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-port-pack/src/carry.rs | 10 +- .../src/legacy_structure_mods/ctov.rs | 179 +++ .../legacy_structure_mods/lithostitched.rs | 503 ++++++++ .../src/legacy_structure_mods/mod.rs | 32 + .../src/legacy_structure_mods/yung.rs | 1055 +++++++++++++++++ crates/horizon-port-pack/src/lib.rs | 1 + crates/horizon-port-pack/src/processors.rs | 899 +------------- crates/horizon-port-pack/src/worldgen.rs | 753 +----------- 8 files changed, 1819 insertions(+), 1613 deletions(-) create mode 100644 crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs create mode 100644 crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs create mode 100644 crates/horizon-port-pack/src/legacy_structure_mods/mod.rs create mode 100644 crates/horizon-port-pack/src/legacy_structure_mods/yung.rs diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index 03b5d7dc9..42c0483b4 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -814,7 +814,7 @@ pub fn carry( if kind == "structure" { let path = rel.trim_start_matches("worldgen/structure/"); let structure = format!("{ns}:{}", path.trim_end_matches(".json")); - changed |= crate::worldgen::disables(&structure, &mut v); + changed |= crate::legacy_structure_mods::yung::disables(&structure, &mut v); changed |= crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts); } @@ -829,9 +829,9 @@ pub fn carry( // Additions to other sets and pools, as files the game merges. let modifier = serde_json::from_slice::(&bytes).ok(); let types = &mut report.worldgen_types; - if let Some((kind, mut added)) = - modifier.and_then(|v| crate::worldgen::modifier(&v, loaded, types)) - { + if let Some((kind, mut added)) = modifier.and_then(|v| { + crate::legacy_structure_mods::lithostitched::modifier(&v, loaded, types) + }) { crate::processors::carry( kind, &mut added, @@ -910,7 +910,7 @@ pub fn carry( } // Entries the mod adds to other structure sets in Java code, for the // structures it has. - for (file, set, entries) in crate::worldgen::code_set_entries(id) { + for (file, set, entries) in crate::legacy_structure_mods::ctov::code_set_entries(id) { let entries: Vec = entries .into_iter() .filter(|(s, _)| { diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs b/crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs new file mode 100644 index 000000000..af46174ae --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs @@ -0,0 +1,179 @@ +//! Choice Theorem's Overhauled Village: the entries it adds to other +//! structure sets in Java code, and its `modular_compat` processor. +use crate::processors::{ProcessorData, referenced}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds +/// to vanilla's `villages` and `pillager_outposts` sets in Java code +/// (`CTOV.registerstructure`, through lithostitched), with its default +/// config: every village type in three sizes, weighted 10, 4 and 1, and +/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each). +const CTOV_VILLAGES: [&str; 21] = [ + "beach", + "christmas", + "desert", + "desert_oasis", + "dark_forest", + "jungle", + "jungle_tree", + "mesa", + "mesa_fortified", + "mountain", + "mountain_alpine", + "mushroom", + "plains", + "plains_fortified", + "savanna", + "savanna_na", + "snowy_igloo", + "swamp", + "swamp_fortified", + "taiga", + "taiga_fortified", +]; +const CTOV_OUTPOSTS: [&str; 11] = [ + "beach", + "dark_forest", + "desert", + "jungle", + "badlands", + "mountain", + "plains", + "savanna", + "snowy", + "swamp", + "taiga", +]; + +/// The entries a mod adds to other structure sets in Java code, as its +/// default config has them: (file name, set, `[(structure, weight)]`). +/// Lithostitched appends them in the order of a hash map of every modifier +/// in the pack, which carry cannot know; they are written in the order the +/// mod registers them. Each set picks by weight, so how often each starts +/// is the same. +pub(crate) fn code_set_entries( + mod_id: &str, +) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> { + match mod_id { + "ctov" => { + let outposts = CTOV_OUTPOSTS + .iter() + .map(|v| (format!("ctov:pillager_outpost_{v}"), 1)) + .collect(); + let villages = [("small", 10), ("medium", 4), ("large", 1)] + .into_iter() + .flat_map(|(size, weight)| { + CTOV_VILLAGES + .iter() + .map(move |v| (format!("ctov:{size}/village_{v}"), weight)) + }) + .collect(); + vec![ + ("pillager_outposts", "minecraft:pillager_outposts", outposts), + ("villages", "minecraft:villages", villages), + ] + } + _ => Vec::new(), + } +} + +/// Choice Theorem's Overhauled Village's processor that runs the list +/// `reference` when mod `modid` is loaded (ModularCompatProcessor). +const MODULAR_COMPAT: &str = "ctov:modular_compat"; + +/// Notes which mods its compat processors name are `loaded`. +pub(crate) fn mark_loaded(data: &mut ProcessorData, loaded: &dyn Fn(&str) -> bool) { + fn walk(v: &Value, out: &mut BTreeSet) { + match v { + Value::Object(o) => { + if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) { + if let Some(id) = o.get("modid").and_then(Value::as_str) { + out.insert(id.to_owned()); + } + } + o.values().for_each(|v| walk(v, out)); + } + Value::Array(a) => a.iter().for_each(|v| walk(v, out)), + _ => {} + } + } + let mut named = BTreeSet::new(); + data.lists.values().for_each(|l| walk(l, &mut named)); + data.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect(); +} + +/// A `ctov:modular_compat` processor in a list being carried, at `depth` +/// (see [`super::lithostitched`]'s references): counted in `carried`, and +/// the processors of the list it names when its mod is loaded, else none. +/// `None` for any other processor, or past the depth limit. +pub(super) fn modular_compat( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, + depth: usize, +) -> Option> { + if p["processor_type"] != MODULAR_COMPAT || depth >= 8 { + return None; + } + *carried.entry(MODULAR_COMPAT.into()).or_default() += 1; + let loaded = p["modid"] + .as_str() + .is_some_and(|m| data.compat_loaded.contains(m)); + Some( + loaded + .then(|| referenced(&p["reference"], data)) + .flatten() + .unwrap_or_default(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::processors::carry; + use serde_json::json; + + #[test] + fn ctov_joins_vanillas_villages_and_outposts() { + let sets = code_set_entries("ctov"); + let (file, set, outposts) = &sets[0]; + assert_eq!( + (*file, *set), + ("pillager_outposts", "minecraft:pillager_outposts") + ); + assert_eq!(outposts.len(), 11); + assert!(outposts.iter().all(|(_, w)| *w == 1)); + let (_, set, villages) = &sets[1]; + assert_eq!(*set, "minecraft:villages"); + assert_eq!(villages.len(), 63); + assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10)); + assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4)); + assert_eq!( + villages[62], + ("ctov:large/village_taiga_fortified".into(), 1) + ); + assert!(code_set_entries("mvs").is_empty()); + } + + #[test] + fn modular_compat_runs_its_list_only_with_its_mod() { + let mut data = ProcessorData::default(); + let swap = json!({"processor_type": "minecraft:rule", "rules": []}); + data.lists + .insert("v:house_ns".into(), json!({"processors": [swap.clone()]})); + let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"}); + let gravity = json!({"processor_type": "minecraft:gravity"}); + data.lists.insert( + "v:house".into(), + json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}), + ); + data.mark_loaded(&|m| m == "ns"); + assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()])); + let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut v, &data, &mut carried)); + assert_eq!(v, json!({"processors": [swap, gravity]})); + assert_eq!(carried["ctov:modular_compat"], 2); + } +} diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs b/crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs new file mode 100644 index 000000000..54415a76a --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs @@ -0,0 +1,503 @@ +//! Lithostitched: its jigsaw structure, its worldgen modifiers and its +//! processors. +use super::ctov; +use crate::processors::{ProcessorData, carry_all, processors, referenced}; +use crate::worldgen::{ENHANCED_TERRAIN, Upgrade, start_checks}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +/// A `structure` file of Lithostitched's jigsaw type as vanilla's, with the +/// start rules it shares with the other libraries' jigsaws (`worldgen`'s +/// `start_checks`). `None` for any other file. +pub(crate) fn upgrade( + kind: &str, + v: &mut Value, + lost: &mut BTreeMap, +) -> Option { + if kind != "structure" || v["type"] != "lithostitched:jigsaw" { + return None; + } + start_checks(v, "lowest", lost, false); + if v.as_object_mut() + .and_then(|o| o.remove(ENHANCED_TERRAIN)) + .is_some() + { + *lost.entry(ENHANCED_TERRAIN.into()).or_default() += 1; + } + v["type"] = "minecraft:jigsaw".into(); + Some(true) +} + +/// A lithostitched worldgen modifier +/// (`data//lithostitched/worldgen_modifier/`) that adds to structure +/// sets or template pools, as a file the game merges into them (the key +/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The +/// modifier's conditions are checked against `loaded`, the mods ported +/// along: a compat addition for a mod that is not would place that mod's +/// blocks, which the game does not have. Other modifier types are left out. +/// Both are counted in `report`. +pub(crate) fn modifier( + v: &Value, + loaded: &dyn Fn(&str) -> bool, + report: &mut Upgrade, +) -> Option<(&'static str, Value)> { + let t = v["type"].as_str().unwrap_or_default(); + let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1; + let (kind, targets, from, to) = match t { + "lithostitched:add_structure_set_entries" => { + ("structure_set", "structure_sets", "entries", "structures") + } + "lithostitched:add_template_pool_elements" => { + ("template_pool", "template_pools", "elements", "elements") + } + _ => { + left(t); + return None; + } + }; + if !conditions_hold(v, loaded) { + left("conditions"); + return None; + } + let targets: Option> = match &v[targets] { + Value::String(s) => Some(vec![s.as_str()]), + Value::Array(a) => a.iter().map(Value::as_str).collect(), + _ => None, + }; + let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#'))) + else { + left("target"); + return None; + }; + let entries = v[from].as_array().cloned().unwrap_or_default(); + for target in &targets { + *report.added_to.entry((*target).to_owned()).or_default() += entries.len(); + } + Some(( + kind, + serde_json::json!({"horizon:add_to": targets, to: entries}), + )) +} + +/// Whether a modifier's load conditions hold: lithostitched's `predicate`, +/// and the loader's conditions (NeoForge's, else Fabric's). A condition +/// type not known here does not hold. +fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let all = |list: &Value, test: &dyn Fn(&Value) -> bool| { + list.as_array().is_some_and(|a| a.iter().all(test)) + }; + fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| predicate(q, loaded); + let list = &p["predicates"]; + match p["type"] + .as_str() + .map(|t| t.trim_start_matches("lithostitched:")) + { + Some("true") => true, + Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded), + Some("not") => !predicate(&p["predicate"], loaded), + Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)), + Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| neoforge(q, loaded); + match c["type"].as_str() { + Some("neoforge:true") => true, + Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded), + Some("neoforge:not") => !neoforge(&c["value"], loaded), + Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| fabric(q, loaded); + let mods = || { + c["values"] + .as_array() + .into_iter() + .flatten() + .map(Value::as_str) + }; + match c["condition"].as_str() { + Some("fabric:true") => true, + Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)), + Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)), + Some("fabric:not") => !fabric(&c["value"], loaded), + Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded)); + let loader = match ( + v.get("neoforge:conditions"), + v.get("fabric:load_conditions"), + ) { + (Some(c), _) => all(c, &|c| neoforge(c, loaded)), + // One condition or a list of them. + (None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)), + (None, Some(c)) => fabric(c, loaded), + (None, None) => true, + }; + litho && loader +} + +/// The data form of one of Lithostitched's processors: the processors to put +/// in its place, or `None` when it has none (or is not Lithostitched's). +pub(crate) fn processor( + kind: &str, + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> Option> { + match kind { + "lithostitched:apply_random" => apply_random(p, data, carried).map(|p| vec![p]), + "lithostitched:condition" => condition(p, data, carried).map(|p| vec![p]), + "lithostitched:block_swap" => { + // The same map; the game's swap keeps the properties both have. + p["blocks"].as_object()?; + Some(vec![ + json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]}), + ]) + } + "lithostitched:set_block" => { + // A simple or weighted state provider, the block entity left as + // it is. + let provider = p["state_provider"]["type"].as_str()?; + let modifier = p["block_entity_modifier"]["type"].as_str(); + let plain = + modifier.is_none_or(|m| m.trim_start_matches("minecraft:") == "passthrough"); + if !plain + || !matches!( + provider, + "minecraft:simple_state_provider" | "minecraft:weighted_state_provider" + ) + { + return None; + } + let mut out = p.clone(); + out["processor_type"] = "horizon:set_block".into(); + if let Some(o) = out.as_object_mut() { + o.remove("block_entity_modifier"); + } + Some(vec![out]) + } + _ => None, + } +} + +/// The references (Lithostitched's, and CTOV's compat processors) in a +/// processor list written in; whether any was. +pub(crate) fn expand_references( + list: Vec, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> (Vec, bool) { + references(list, data, carried, 0) +} + +/// A processor list inside a carried processor: an id stays (the game reads +/// that file, carried on its own); an inline one is carried here. +fn nested(list: &Value, data: &ProcessorData, carried: &mut BTreeMap) -> Value { + let mut list = list.clone(); + if let Some(ps) = processors(&mut list) { + *ps = carry_all(std::mem::take(ps), data, carried).0; + } + list +} + +/// Lithostitched's `apply_random` as `horizon:apply_random`: its weighted +/// lists, or its set of lists at weight 1. A tag is not carried. +fn apply_random( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> Option { + let lists = &p["processor_lists"]; + let weighted = lists.as_array().is_some_and(|a| { + a.iter() + .all(|e| e.get("weight").is_some() && e.get("data").is_some()) + }); + let entries: Vec<(Value, Value)> = if weighted { + lists + .as_array()? + .iter() + .map(|e| (e["weight"].clone(), e["data"].clone())) + .collect() + } else { + match lists { + Value::String(id) if !id.starts_with('#') => vec![(1.into(), lists.clone())], + Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => { + vec![(1.into(), lists.clone())] + } + Value::Array(a) + if a.iter() + .all(|x| x.as_str().is_some_and(|s| !s.starts_with('#')) || x.is_object()) => + { + a.iter().map(|x| (1.into(), x.clone())).collect() + } + Value::Object(_) => vec![(1.into(), lists.clone())], + _ => return None, + } + }; + let lists: Vec = entries + .into_iter() + .map(|(weight, list)| json!({"weight": weight, "data": nested(&list, data, carried)})) + .collect(); + let mut out = json!({"processor_type": "horizon:apply_random", "processor_lists": lists}); + if let Some(mode) = p.get("mode") { + out["mode"] = mode.clone(); + } + Some(out) +} + +/// Lithostitched's `condition` as `horizon:condition`, when the game runs +/// every condition in it (true, all_of, any_of, not, random_chance, +/// matching_blocks with plain property values); else it stays Java. +fn condition( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> Option { + fn runs(c: &Value) -> bool { + if let Some(all) = c.as_array() { + return all.iter().all(runs); + } + let kind = c["type"].as_str().unwrap_or_default(); + match kind.strip_prefix("lithostitched:").unwrap_or(kind) { + "true" | "random_chance" => true, + "all_of" | "any_of" => c["conditions"] + .as_array() + .is_some_and(|a| a.iter().all(runs)), + "not" => runs(&c["condition"]), + "matching_blocks" => c.get("properties").is_none_or(|p| { + p.as_object() + .is_some_and(|o| o.values().all(Value::is_string)) + }), + _ => false, + } + } + if !runs(&p["if_true"]) { + return None; + } + // One processor or a list of them. + let mut branch = |key: &str| -> Value { + let list = match p.get(key) { + None => Vec::new(), + Some(Value::Array(a)) => a.clone(), + Some(one) => vec![one.clone()], + }; + carry_all(list, data, carried).0.into() + }; + let (then, otherwise) = (branch("then"), branch("else")); + let mut out = json!({"processor_type": "horizon:condition", "if_true": p["if_true"], + "then": then, "else": otherwise}); + if let Some(mode) = p.get("random_mode") { + out["random_mode"] = mode.clone(); + } + Some(out) +} + +/// Lithostitched's references in a list, each replaced by the processors of +/// the lists it names, in order (references in them too, to a depth of 8). +/// One naming a tag or a list the mod does not have stays, to be dropped. +/// Whether any was replaced. +fn references( + list: Vec, + data: &ProcessorData, + carried: &mut BTreeMap, + depth: usize, +) -> (Vec, bool) { + let mut out = Vec::with_capacity(list.len()); + let mut changed = false; + for p in list { + if let Some(inner) = ctov::modular_compat(&p, data, carried, depth) { + changed = true; + out.extend(references(inner, data, carried, depth + 1).0); + continue; + } + let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) + .then(|| referenced(&p["processor_lists"], data)) + .flatten(); + match named { + Some(inner) => { + *carried.entry("lithostitched:reference".into()).or_default() += 1; + out.extend(references(inner, data, carried, depth + 1).0); + changed = true; + } + None => out.push(p), + } + } + (out, changed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::legacy_structure_mods::data; + use crate::processors::carry; + + #[test] + fn modifiers_add_to_sets_and_pools() { + let mut report = Upgrade::default(); + let only_fd = |m: &str| m == "farmersdelight"; + let set = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "minecraft:villages", + "entries": [{"structure": "x:village", "weight": 4}]}); + let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap(); + assert_eq!(kind, "structure_set"); + assert_eq!( + added, + json!({"horizon:add_to": ["minecraft:villages"], + "structures": [{"structure": "x:village", "weight": 4}]}) + ); + // A compat addition holds only when its mod is ported along. + let pool = |modid: &str| { + json!({"type": "lithostitched:add_template_pool_elements", + "neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}], + "fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]}, + "template_pools": ["x:houses", "y:houses"], + "elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element", + "location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]}) + }; + let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap(); + assert_eq!(kind, "template_pool"); + assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"])); + assert_eq!(added["elements"][0]["weight"], 5); + assert!(modifier(&pool("create"), &only_fd, &mut report).is_none()); + // Fabric's conditions when there are no NeoForge ones; lithostitched's own. + let fabric = json!({"type": "lithostitched:add_structure_set_entries", + "fabric:load_conditions": [{"condition": "fabric:not", + "value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}], + "predicate": {"type": "lithostitched:all_of", "predicates": [ + {"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"}, + {"type": "lithostitched:true"}]}, + "structure_sets": "minecraft:villages", "entries": []}); + assert!(modifier(&fabric, &only_fd, &mut report).is_some()); + let tagged = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "#x:sets", "entries": []}); + assert!(modifier(&tagged, &only_fd, &mut report).is_none()); + let features = json!({"type": "lithostitched:add_features"}); + assert!(modifier(&features, &only_fd, &mut report).is_none()); + assert_eq!( + report.added_to, + BTreeMap::from([ + ("minecraft:villages".into(), 1), + ("x:houses".into(), 1), + ("y:houses".into(), 1), + ]) + ); + assert_eq!( + report.modifiers_left, + BTreeMap::from([ + ("conditions".into(), 1), + ("lithostitched:add_features".into(), 1), + ("target".into(), 1), + ]) + ); + } + + #[test] + fn lithostitched_block_swaps_become_the_games() { + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}, + {"processor_type": "lithostitched:block_swap", "blocks": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0], + json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}) + ); + // A map that is not one stays Java (dropped later). + assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); + } + + #[test] + fn lithostitched_references_are_written_in() { + let mut data = data(); + let gravity = json!({"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}); + data.lists + .insert("v:road".into(), json!({"processors": [gravity.clone()]})); + data.lists.insert( + "v:house".into(), + json!({"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": "v:road"}, + {"processor_type": "lithostitched:block_swap", "blocks": {"minecraft:dirt": "minecraft:grass_block"}}]}), + ); + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": ["v:house", "v:road"]}, + {"processor_type": "lithostitched:reference", "processor_lists": "#v:roads"}, + {"processor_type": "lithostitched:reference", "processor_lists": ["v:nowhere"]}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data, &mut carried)); + let p = list["processors"].as_array().unwrap(); + // House (its own reference to road first, then its swap), then road; + // the swap inside is carried too. + assert_eq!(p[0], gravity); + assert_eq!(p[1]["processor_type"], "horizon:block_swap"); + assert_eq!(p[2], gravity); + // A tag or a list the mod lacks stays, to be dropped. + assert_eq!(p[3]["processor_lists"], "#v:roads"); + assert_eq!(p[4]["processor_lists"], json!(["v:nowhere"])); + assert_eq!(carried["lithostitched:reference"], 2); + } + + #[test] + fn lithostitched_random_and_condition_become_the_games() { + let mut data = data(); + let swap = json!({"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); + data.lists + .insert("v:green".into(), json!({"processors": [swap.clone()]})); + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [ + {"weight": 3, "data": "minecraft:empty"}, + {"weight": 1, "data": {"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": "v:green"}, + {"processor_type": "v:java"}]}}]}, + {"processor_type": "lithostitched:apply_random", "mode": "per_block", + "processor_lists": ["v:green", "v:red"]}, + {"processor_type": "lithostitched:apply_random", "mode": "per_block", + "processor_lists": "#v:colours"}, + {"processor_type": "lithostitched:condition", + "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], + "then": swap, "else": {"processor_type": "lithostitched:set_block", "state_provider": + {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}}, + {"processor_type": "lithostitched:condition", + "if_true": {"type": "lithostitched:matching_biomes", "biomes": "#c:is_cold"}, + "then": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data, &mut carried)); + let p = list["processors"].as_array().unwrap(); + let green = json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); + // Inline lists are carried; Java left in them is dropped later. + assert_eq!( + p[0], + json!({"processor_type": "horizon:apply_random", "mode": "per_piece", "processor_lists": [ + {"weight": 3, "data": "minecraft:empty"}, + {"weight": 1, "data": {"processors": [green.clone(), {"processor_type": "v:java"}]}}]}) + ); + assert_eq!( + p[1]["processor_lists"], + json!([{"weight": 1, "data": "v:green"}, {"weight": 1, "data": "v:red"}]) + ); + assert_eq!(p[2]["processor_type"], "lithostitched:apply_random"); + assert_eq!( + p[3], + json!({"processor_type": "horizon:condition", + "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], + "then": [green], "else": [{"processor_type": "horizon:set_block", "state_provider": + {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}]}) + ); + assert_eq!(p[4]["processor_type"], "lithostitched:condition"); + assert_eq!(carried["lithostitched:apply_random"], 2); + assert_eq!(carried["lithostitched:condition"], 1); + } +} diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/mod.rs b/crates/horizon-port-pack/src/legacy_structure_mods/mod.rs new file mode 100644 index 000000000..49db376bc --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/mod.rs @@ -0,0 +1,32 @@ +//! The conversion of three families of structure mods' data, kept apart from +//! the general conversion code (`worldgen`, `processors`, `carry`): +//! +//! - [`yung`]: YUNG's API and the mods built on it (Better Dungeons, Desert +//! Temples, Jungle Temples, Witch Huts, Ocean Monuments, Strongholds, +//! Fortresses, Mineshafts), written under `horizon:yungsapi` and the other +//! keys `horizon_world::worldgen::structure::yung` reads. +//! - [`lithostitched`]: Lithostitched's jigsaw, worldgen modifiers and +//! processors. +//! - [`ctov`]: Choice Theorem's Overhauled Village's code-registered set +//! entries and its modular compat processor. +//! +//! The general code reaches them only through the `pub(crate)` entry points +//! of these three modules. Nothing in them is used by another mod's +//! conversion. +pub(crate) mod ctov; +pub(crate) mod lithostitched; +pub(crate) mod yung; + +#[cfg(test)] +fn data() -> crate::processors::ProcessorData { + let mut d = crate::processors::ProcessorData::default(); + d.spawners.insert( + "repurposed_structures:dungeons/badlands".into(), + vec![ + ("minecraft:husk".into(), 10.), + ("minecraft:cave_spider".into(), 3.), + ], + ); + d.replace_vanilla.insert(("mvs".into(), "village".into())); + d +} diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/yung.rs b/crates/horizon-port-pack/src/legacy_structure_mods/yung.rs new file mode 100644 index 000000000..26dd25923 --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/yung.rs @@ -0,0 +1,1055 @@ +//! YUNG's API and the mods built on it: structures, placements, pool +//! elements and processors. +use crate::worldgen::{ENHANCED_TERRAIN, HORIZON_ENHANCED_TERRAIN, moogs_terrain, placement_rules}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +/// YUNG's placements: vanilla's random spread with an enhanced exclusion +/// zone (several sets), plus, for the temples, no start near an ocean or a +/// river, and for strongholds, starts only in odd rings around the origin. +const YUNG_SPREADS: [&str; 4] = [ + "yungsapi:enhanced_random_spread", + "betterdeserttemples:desert_temple", + "betterjungletemples:jungle_temple", + "betterstrongholds:stronghold", +]; +/// YUNG's structures and the vanilla structure type each one's mod turns +/// off (its DisableVanilla*Mixin, on by default in each mod's config). +const YUNG_REPLACES: [(&str, &str); 7] = [ + ( + "betterdeserttemples:desert_temple", + "minecraft:desert_pyramid", + ), + ( + "betterjungletemples:jungle_temple", + "minecraft:jungle_temple", + ), + ("betterwitchhuts:witch_hut", "minecraft:swamp_hut"), + ( + "betteroceanmonuments:ocean_monument", + "minecraft:ocean_monument", + ), + ("betterstrongholds:stronghold", "minecraft:stronghold"), + ("betterfortresses:fortress", "minecraft:fortress"), + ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), +]; + +/// A `structure` or `structure_set` file of YUNG's types as vanilla's: its +/// jigsaw, and its placements. `None` for any other file. +pub(crate) fn upgrade( + kind: &str, + v: &mut Value, + set_tags: &BTreeMap>, + lost: &mut BTreeMap, +) -> Option { + match kind { + "structure" => match v["type"].as_str() { + // Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a + // config switch that ships on. + Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => { + yung_structure(v, lost); + Some(true) + } + _ => None, + }, + "structure_set" => match v["placement"]["type"].as_str() { + Some(t) if YUNG_SPREADS.contains(&t) => { + let t = t.to_owned(); + yung_placement(&t, &mut v["placement"], set_tags, lost); + Some(true) + } + _ => None, + }, + _ => None, + } +} + +/// A pool element of YUNG's type as vanilla's; whether it was one. +pub(crate) fn upgrade_pool_element( + element: &mut Value, + lost: &mut BTreeMap, +) -> bool { + if element["element_type"] != "yungsapi:yung_single_element" { + return false; + } + yung_element(element, lost); + true +} + +/// YUNG's API's jigsaw as vanilla's, laid out by its own assembler in the +/// game (`horizon:yungsapi`, `horizon_world::worldgen::structure::yung`): +/// the heights pieces stay within move under the key, its terrain +/// adaptation under `horizon:enhanced_terrain_adaptation`. A start offset in +/// the chunk is lost. +fn yung_structure(v: &mut Value, lost: &mut BTreeMap) { + let Some(o) = v.as_object_mut() else { + return; + }; + o.insert("type".into(), "minecraft:jigsaw".into()); + let mut rules = serde_json::Map::new(); + for key in ["min_y", "max_y"] { + if let Some(y) = o.remove(key) { + rules.insert(key.into(), y); + } + } + // YungJigsawStructure's adaptation (NONE by default): every piece's + // junctions, and the start's box grown by its radius. + let own = o.remove(ENHANCED_TERRAIN); + let mut kernel = yung_terrain(own.as_ref().unwrap_or(&Value::Null), lost); + kernel["rigid_junctions"] = true.into(); + kernel["inflate"] = true.into(); + o.insert(HORIZON_ENHANCED_TERRAIN.into(), kernel); + for key in ["x_offset_in_chunk", "z_offset_in_chunk"] { + if o.remove(key).is_some_and(|n| n != 0) { + *lost.entry(key.into()).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// YUNG's single pool element as vanilla's, its rules under +/// `horizon:yungsapi`: name and `max_count`, depth range, priority, +/// `ignore_bounds`, its condition, dead-end pool and modifiers; its terrain +/// adaptation under `horizon:enhanced_terrain_adaptation`. +fn yung_element(element: &mut Value, lost: &mut BTreeMap) { + let Some(o) = element.as_object_mut() else { + return; + }; + o.insert( + "element_type".into(), + "minecraft:single_pool_element".into(), + ); + let mut rules = serde_json::Map::new(); + for (from, to) in [ + ("name", "name"), + ("max_count", "max_count"), + ("min_required_depth", "min_depth"), + ("max_possible_depth", "max_depth"), + ("is_priority", "priority"), + ("ignore_bounds", "ignore_bounds"), + ] { + if let Some(x) = o.remove(from) { + rules.insert(to.into(), x); + } + } + if let Some(c) = o.remove("condition") { + rules.insert("condition".into(), yung_condition(&c, lost)); + } + // A piece's own adaptation, NONE included, replaces its structure's. + if let Some(a) = o.remove(ENHANCED_TERRAIN) { + o.insert(HORIZON_ENHANCED_TERRAIN.into(), yung_terrain(&a, lost)); + } + if let Some(pool) = o.remove("deadend_pool").filter(Value::is_string) { + rules.insert("deadend_pool".into(), pool); + } + let modifiers: Vec = o + .remove("modifiers") + .and_then(|m| m.as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|m| yung_modifier(m, lost)) + .collect(); + if !modifiers.is_empty() { + rules.insert("modifiers".into(), modifiers.into()); + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// One of YUNG's structure modifiers in the game's terms: its condition and +/// its transform and delay_generation actions, on the piece itself (`self`, +/// the API's only target). Another target loses the modifier, another action +/// just that action. +fn yung_modifier(m: &Value, lost: &mut BTreeMap) -> Option { + let target = m["target_selector"]["type"].as_str().unwrap_or_default(); + if target != "yungsapi:self" { + *lost + .entry(format!("yungsapi modifier target {target}")) + .or_default() += 1; + return None; + } + let mut actions = Vec::new(); + for a in m["actions"].as_array().into_iter().flatten() { + let int = |k: &str| a[k].as_i64().unwrap_or(0); + match a["type"].as_str().unwrap_or_default() { + "yungsapi:transform" => actions.push(serde_json::json!({"type": "transform", + "output": a["output"].clone(), + "offset": [int("x_offset"), int("y_offset"), int("z_offset")]})), + "yungsapi:delay_generation" => { + actions.push(serde_json::json!({"type": "delay_generation"})) + } + other => { + *lost + .entry(format!("yungsapi modifier action {other}")) + .or_default() += 1 + } + } + } + let condition = match m.get("condition") { + Some(c) => yung_condition(c, lost), + None => serde_json::json!({"type": "true"}), + }; + Some(serde_json::json!({"condition": condition, "actions": actions})) +} + +/// YUNG's API's terrain adaptation as the game's kernel: its two presets +/// spelled out, NONE (also the default) as size 0. An aquifer override +/// (none of ATM10's) is lost. +fn yung_terrain(a: &Value, lost: &mut BTreeMap) -> Value { + let kernel = |size: i32, distance: i32, top: &str, bottom: &str| { + serde_json::json!({"kernel_size": size, "kernel_distance": distance, + "top": top, "bottom": bottom}) + }; + match a["type"].as_str() { + Some("yungsapi:carved_top_no_beard_large") => kernel(24, 16, "carve", "none"), + Some("yungsapi:carved_top_no_beard_small") => kernel(12, 6, "carve", "none"), + Some("yungsapi:custom") => { + let mut out = serde_json::Map::new(); + for key in [ + "kernel_size", + "kernel_distance", + "top", + "bottom", + "bottom_offset", + "padding", + ] { + if let Some(x) = a.get(key) { + out.insert(key.into(), x.clone()); + } + } + if a.get("aquifer_override") + .is_some_and(|x| x["type"] != "yungsapi:none") + { + *lost.entry("yungsapi aquifer_override".into()).or_default() += 1; + } + moogs_terrain(&out.into(), lost).unwrap_or_else(|| kernel(0, 0, "none", "none")) + } + None | Some("yungsapi:none") => kernel(0, 0, "none", "none"), + Some(other) => { + *lost + .entry(format!("yungsapi terrain adaptation {other}")) + .or_default() += 1; + kernel(0, 0, "none", "none") + } + } +} + +/// One of YUNG's structure conditions in the game's terms. `mod_loaded` +/// holds for Minecraft alone: a mod that needs code is not ported, and the +/// pieces it guards would place its blocks. A condition the game does not +/// have does not hold, and is counted. +fn yung_condition(c: &Value, lost: &mut BTreeMap) -> Value { + let t = c["type"].as_str().unwrap_or_default(); + let list = |lost: &mut BTreeMap| -> Value { + let all = c["conditions"].as_array().into_iter().flatten(); + all.map(|x| yung_condition(x, lost)) + .collect::>() + .into() + }; + let opt = |k: &str| c.get(k).cloned().unwrap_or(Value::Null); + match t.trim_start_matches("yungsapi:") { + "always_true" => serde_json::json!({"type": "true"}), + "not" => { + serde_json::json!({"type": "not", "condition": yung_condition(&c["condition"], lost)}) + } + "all_of" => serde_json::json!({"type": "all_of", "conditions": list(lost)}), + "any_of" => serde_json::json!({"type": "any_of", "conditions": list(lost)}), + "depth" => serde_json::json!({"type": "depth", + "min_depth": opt("min_required_depth"), "max_depth": opt("max_possible_depth")}), + "altitude" => serde_json::json!({"type": "altitude", + "bottom": opt("bottom_cutoff_y"), "top": opt("top_cutoff_y")}), + "random_chance" => serde_json::json!({"type": "random_chance", "chance": opt("chance")}), + "rotation" => serde_json::json!({"type": "rotation", "rotations": opt("rotations")}), + "piece_in_horizontal_direction" => { + // "yungsapi:all" (or no list) matches any piece. + let pieces: Vec = c["pieces"].as_array().cloned().unwrap_or_default(); + let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all"); + serde_json::json!({"type": "piece_in_horizontal_direction", + "pieces": if any { Vec::new() } else { pieces }, + "range": opt("range"), "rotation": opt("rotation")}) + } + // The game reads "yungsapi:all" (or no list) as any piece. + "piece_in_range" => serde_json::json!({"type": "piece_in_range", + "pieces": c.get("pieces").cloned().unwrap_or_else(|| Vec::::new().into()), + "horizontal_range": opt("horizontal_range"), "above_range": opt("above_range"), + "below_range": opt("below_range")}), + "mod_loaded" if c["modid"] == "minecraft" => serde_json::json!({"type": "true"}), + "mod_loaded" => serde_json::json!({"type": "false"}), + _ => { + *lost.entry(format!("yungsapi condition {t}")).or_default() += 1; + serde_json::json!({"type": "false"}) + } + } +} + +/// One of YUNG's placements as vanilla's random spread with `horizon:` keys: +/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' +/// ocean and river search (findBiomeHorizontal around the chunk's middle +/// block at y 120, 48 blocks, every 2 quarts) as `horizon:avoid_biomes`; the +/// strongholds' rings as `horizon:ring_sections`. +fn yung_placement( + t: &str, + p: &mut Value, + set_tags: &BTreeMap>, + lost: &mut BTreeMap, +) { + placement_rules(p, set_tags, lost); + p["type"] = "minecraft:random_spread".into(); + let Some(o) = p.as_object_mut() else { + return; + }; + match t { + "betterdeserttemples:desert_temple" | "betterjungletemples:jungle_temple" => { + o.insert( + "horizon:avoid_biomes".into(), + serde_json::json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}), + ); + } + "betterstrongholds:stronghold" => { + let mut rings = serde_json::Map::new(); + for (from, to) in [ + ("chunk_distance_to_first_ring", "distance_to_first_ring"), + ("ring_chunk_thickness", "thickness"), + ("max_ring_section", "max_section"), + ] { + if let Some(n) = o.remove(from) { + rings.insert(to.into(), n); + } + } + o.insert("horizon:ring_sections".into(), rings.into()); + } + _ => {} + } +} + +/// Marks a YUNG's structure that the game can start (its type is vanilla's +/// after the upgrade) with the vanilla type its mod turns off, under +/// `horizon:disables`. One the game cannot start leaves the vanilla +/// structure in place, so the world keeps one of the two. +pub(crate) fn disables(id: &str, v: &mut Value) -> bool { + let Some((_, vanilla)) = YUNG_REPLACES.iter().find(|(s, _)| id.starts_with(s)) else { + return false; + }; + if !v["type"] + .as_str() + .is_some_and(|t| t.starts_with("minecraft:")) + { + return false; + } + v["horizon:disables"] = serde_json::json!([vanilla]); + true +} + +/// The game's type for the YUNG's processors that place blocks past their +/// template, which keep their fields (`horizon-world`'s `pillars.rs`). +pub(crate) fn pillar_type(kind: &str) -> Option<&'static str> { + Some(match kind { + "betterfortresses:pillar_processor" | "betterjungletemples:pillar_processor" => { + "horizon:yung_pillar" + } + _ => return None, + }) +} + +/// The data form of one of YUNG's processors: the processors to put in its +/// place, or `None` when it has none (or is not YUNG's). +pub(crate) fn processor(kind: &str, p: &Value) -> Option> { + let (ns, _) = kind.split_once(':')?; + Some(match kind { + // Better Fortresses' stair supports get the blocks its Java code + // names. + "betterfortresses:stair_pillar_processor" => { + vec![json!({"processor_type": "horizon:stair_pillar", + "blocks": {"minecraft:stone_brick_stairs": "minecraft:red_nether_brick_stairs", + "minecraft:purpur_stairs": "minecraft:red_nether_bricks"}, + "front": "minecraft:red_nether_brick_stairs", + "pillar": "minecraft:red_nether_bricks"})] + } + _ if ns == "betterdeserttemples" + && let Some(processor) = desert_temple(kind) => + { + vec![processor] + } + "betterdungeons:small_dungeon_chest_processor" => { + // Its config's defaults: one chest at least, two at most, a + // fifth of the others kept until then; ChestBlock covers both. + vec![json!({"processor_type": "horizon:count_cap", + "blocks": ["minecraft:chest", "minecraft:trapped_chest"], + "min": 1, "max": 2, "chance": 0.2f32 as f64, + "replacement": block("minecraft:cave_air")})] + } + "betterwitchhuts:leg_processor" => vec![yung_leg( + "minecraft:brown_stained_glass", + json!({"id": "minecraft:oak_log", "properties": {"axis": "y"}}), + false, + )], + "betterwitchhuts:fence_leg_processor" => vec![yung_leg( + "minecraft:crimson_fence", + block("minecraft:oak_fence"), + true, + )], + _ if ns == "betteroceanmonuments" => ocean_monument(kind)?, + _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], + _ => return None, + }) +} + +/// YUNG's leg processors (Better Ocean Monuments, Better Witch Huts): a +/// placeholder block becomes `state` and a column of it runs down through +/// air and fluids: the game's `horizon:yung_pillar` with fixed states, and +/// the placeholder's properties kept for the fence legs. +fn yung_leg(target: &str, state: Value, keep_properties: bool) -> Value { + let fixed = json!({"entries": [], "defaultBlockState": state}); + json!({"processor_type": "horizon:yung_pillar", "target_block": block(target), + "target_block_output": fixed, "pillar_states": fixed, + "keep_properties": keep_properties}) +} + +/// Better Ocean Monuments' processors (no fields; what they do is in their +/// Java code): placeholder blocks as vanilla's `rule` or the game's +/// `horizon:pick` (a new `nextFloat` for each chance, as the mod draws), +/// and its sea-level ones as the game's `horizon:flood_air`, +/// `horizon:waterlog` and `horizon:keep_world_block`. +fn ocean_monument(kind: &str) -> Option> { + let rule = |rules: &[(&str, Value)]| { + let rules: Vec = rules + .iter() + .map(|(from, to)| { + json!({"input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": to}) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) + }; + let state = |id: &str, props: Value| json!({"id": id, "properties": props}); + let pick = |from: &str, picks: Vec<(f32, Value)>, default: Value, keep: bool| { + let picks: Vec = picks + .into_iter() + .map(|(below, state)| json!({"below": below as f64, "state": state})) + .collect(); + json!({"processor_type": "horizon:pick", "block": from, "picks": picks, + "default": {"state": default}, "redraw": true, "keep_properties": keep}) + }; + let slabs = |from: &str, slab: &str, otherwise: &str| { + let wet = |t: &str| state(slab, json!({"type": t, "waterlogged": "true"})); + pick( + from, + vec![(0.4, wet("top")), (0.8, wet("bottom"))], + block(otherwise), + false, + ) + }; + // Exposed below 0.1, else weathered below a new 0.3, else oxidized, + // with the placeholder's properties for the stairs and slabs. + let copper = |kind: &str| { + let id = |age: &str| block(&format!("minecraft:{age}{kind}")); + pick( + &format!("minecraft:oxidized_{kind}"), + vec![(0.1, id("exposed_")), (0.3, id("weathered_"))], + id("oxidized_"), + true, + ) + }; + Some(match kind.strip_prefix("betteroceanmonuments:")? { + "random_prismarine_slab_decoration_processor" => vec![slabs( + "minecraft:lime_concrete", + "minecraft:prismarine_slab", + "minecraft:air", + )], + "random_dark_prismarine_slab_decoration_processor" => vec![slabs( + "minecraft:blue_concrete", + "minecraft:dark_prismarine_slab", + "minecraft:water", + )], + "sand_gravel_processor" => { + vec![rule(&[( + "minecraft:yellow_stained_glass", + block("minecraft:gravel"), + )])] + } + "random_oxidization_processor" => [ + "copper", + "cut_copper", + "cut_copper_stairs", + "cut_copper_slab", + ] + .into_iter() + .map(copper) + .collect(), + "structure_void_processor" => vec![json!({"processor_type": "horizon:keep_world_block", + "blocks": ["minecraft:purpur_slab", "minecraft:brown_wool"]})], + "air_processor" => vec![json!({"processor_type": "horizon:flood_air"})], + "waterlog_processor" => vec![json!({"processor_type": "horizon:waterlog"})], + "seagrass_processor" => vec![rule(&[ + ( + "minecraft:red_sandstone_slab", + state("minecraft:tall_seagrass", json!({"half": "lower"})), + ), + ( + "minecraft:end_stone_brick_slab", + state("minecraft:tall_seagrass", json!({"half": "upper"})), + ), + ("minecraft:brick_slab", block("minecraft:seagrass")), + ])], + "random_sponge_processor" => vec![pick( + "minecraft:orange_stained_glass", + vec![(0.75, block("minecraft:wet_sponge"))], + block("minecraft:water"), + false, + )], + "leg_processor" => vec![yung_leg( + "minecraft:blue_stained_glass", + block("minecraft:prismarine_bricks"), + false, + )], + _ => return None, + }) +} + +/// A block state as 26.3 writes it. +fn block(id: &str) -> Value { + json!({"id": id}) +} + +/// Better Desert Temples' placeholder blocks (glass, concrete and wool in +/// the templates) as the mod's processors turn them: the fixed ones as +/// vanilla's `rule`, the random ones as the game's `horizon:pick`, with the +/// mod's bounds on one `nextFloat` (YUNG's BlockStateRandomizer adds its +/// chances up in floats). The ones that read or change the world around +/// (pillars, Diorite's waterlogging) stay dropped. +fn desert_temple(kind: &str) -> Option { + let swap = |from: &str, to: &str| { + json!({"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": block(to)}]}) + }; + let pick = |from: &str, picks: Vec, default: Value| json!({"processor_type": "horizon:pick", "block": from, "picks": picks, "default": default}); + // YUNG's BlockStateRandomizer: an entry wins below the sum of the + // chances so far, summed as floats. + let randomizer = |entries: &[(f32, &str)]| { + let mut bottom = 0f32; + entries + .iter() + .map(|(chance, id)| { + bottom += chance; + json!({"below": bottom as f64, "state": block(id)}) + }) + .collect::>() + }; + let at = |below: f32, id: &str| json!({"below": below as f64, "state": block(id)}); + // Sandstone stairs, upside down, facing Plane.HORIZONTAL.getRandomDirection. + let stairs = || { + let states: Vec = ["north", "east", "south", "west"] + .iter() + .map(|facing| { + json!({"id": "minecraft:sandstone_stairs", "properties": { + "facing": facing, "half": "top", "shape": "straight", "waterlogged": "false"}}) + }) + .collect(); + json!({"states": states}) + }; + Some(match kind.strip_prefix("betterdeserttemples:")? { + "blue_concrete_processor" => swap("minecraft:blue_concrete", "minecraft:blue_terracotta"), + "yellow_concrete_processor" => { + swap("minecraft:yellow_concrete", "minecraft:yellow_terracotta") + } + "red_wool_processor" => swap("minecraft:red_wool", "minecraft:tnt"), + "white_stained_glass_processor" => pick( + "minecraft:white_stained_glass", + randomizer(&[(0.4, "minecraft:cobweb")]), + json!({"state": block("minecraft:air")}), + ), + "polished_diorite_processor" => pick( + "minecraft:polished_diorite", + randomizer(&[(0.6, "minecraft:cut_sandstone")]), + json!({"state": block("minecraft:sandstone")}), + ), + "orange_stained_glass_processor" => { + let mut sus = at(0.01, "minecraft:suspicious_sand"); + sus["nbt"] = json!({"LootTable": "minecraft:archaeology/desert_pyramid"}); + let mut stairs = stairs(); + stairs["below"] = (0.45f32 as f64).into(); + pick( + "minecraft:orange_stained_glass", + vec![ + sus, + at(0.1, "minecraft:sand"), + at(0.2, "minecraft:sandstone"), + stairs, + ], + json!({"state": block("minecraft:cut_sandstone")}), + ) + } + "red_stained_glass_processor" => pick( + "minecraft:red_stained_glass", + vec![at(0.3, "minecraft:sand"), at(0.75, "minecraft:sandstone")], + stairs(), + ), + "pot_processor" => { + // Four sherds, one float each; the pot back to its default state. + let values: Vec = [ + (0.05f32, "archer"), + (0.1, "miner"), + (0.15, "prize"), + (0.2, "skull"), + ] + .iter() + .map(|(below, sherd)| { + json!({"below": *below as f64, "value": format!("minecraft:{sherd}_pottery_sherd")}) + }) + .collect(); + pick( + "minecraft:decorated_pot", + Vec::new(), + json!({"state": block("minecraft:decorated_pot"), "lists": [{ + "key": "sherds", "count": 4, "values": values, "default": "minecraft:brick"}]}), + ) + } + _ => return None, + }) +} + +/// An item as 26.3 saves it. +fn item(id: &str) -> Value { + json!({"id": format!("minecraft:{id}"), "count": 1}) +} + +/// YUNG's processors that make a spawner of a fixed mob (YUNG's API's +/// `MobSpawnerData`), as vanilla's `rule`: every `input` block becomes a +/// spawner with that NBT. +fn yung_spawner(kind: &str, p: &Value) -> Option { + const SPAWNER: &str = "minecraft:spawner"; + // (input block, mob, fields other than the defaults, whether the mob is + // also the only potential, its equipment) + let (input, mob, fields, potential, equipment): (_, _, &[(&str, i64)], _, _) = match kind { + "betterdungeons:mob_spawner_processor" => { + (SPAWNER, p["spawner_mob"].as_str()?, &[], true, None) + } + "betterdungeons:zombie_mob_spawner_processor" => ( + SPAWNER, + "minecraft:zombie", + &[("MaxNearbyEntities", 8)], + true, + None, + ), + "betterdungeons:skeleton_mob_spawner_processor" => ( + SPAWNER, + "minecraft:skeleton", + &[ + ("RequiredPlayerRange", 18), + ("MaxNearbyEntities", 8), + ("MaxSpawnDelay", 650), + ], + true, + None, + ), + "betterdungeons:small_nether_dungeon_mob_spawner_processor" => { + let mob = p["spawner_mob"].as_str()?; + // Wither skeletons get netherite armor that never drops and a + // stone sword (with the mod's default config, they and blazes + // keep their loot). + let armor = (mob == "minecraft:wither_skeleton").then(|| { + json!({ + "equipment": { + "feet": item("netherite_boots"), + "legs": item("netherite_leggings"), + "chest": item("netherite_chestplate"), + "head": item("netherite_helmet"), + "mainhand": item("stone_sword"), + }, + "drop_chances": {"feet": 0.0, "legs": 0.0, "chest": 0.0, "head": 0.0}, + }) + }); + (SPAWNER, mob, &[], true, armor) + } + "betterdungeons:zombie_tombstone_spawner_processor" => ( + "minecraft:black_stained_glass", + "minecraft:skeleton", + &[], + false, + Some(json!({"equipment": {"mainhand": item("iron_sword")}})), + ), + "betterdeserttemples:gravel_processor" => ( + "minecraft:gravel", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + None, + ), + // An empty hand list in 1.21.1: the skeletons spawn without a bow, + // since a spawn entry with more than its id is not finalized. + "betterdeserttemples:bone_block_processor" => ( + "minecraft:bone_block", + "minecraft:skeleton", + &[("RequiredPlayerRange", 32)], + false, + Some(json!({"equipment": {}})), + ), + "betterdeserttemples:infested_cracked_stone_bricks_processor" => ( + "minecraft:infested_cracked_stone_bricks", + "minecraft:silverfish", + &[("RequiredPlayerRange", 24)], + false, + None, + ), + // 1.21.1 ignores the items' old `Count` and `tag` (the shield's + // pattern, the boots' dye): plain items. + "betterdeserttemples:yellow_wool_processor" => ( + "minecraft:yellow_wool", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + Some(json!({"equipment": { + "mainhand": item("golden_sword"), + "offhand": item("shield"), + "feet": item("leather_boots"), + "legs": item("leather_leggings"), + "chest": item("golden_chestplate"), + "head": item("chainmail_helmet"), + }})), + ), + _ => return None, + }; + let mut entity = json!({"id": mob}); + if let Some(Value::Object(extra)) = equipment { + entity.as_object_mut()?.extend(extra); + } + let potentials = match potential { + true => json!([{"data": {"entity": entity.clone()}, "weight": 1}]), + false => json!([]), + }; + let mut nbt = json!({ + "Delay": 20, "MinSpawnDelay": 200, "MaxSpawnDelay": 800, "SpawnCount": 4, + "MaxNearbyEntities": 6, "RequiredPlayerRange": 16, "SpawnRange": 4, + "SpawnData": {"entity": entity}, + "SpawnPotentials": potentials, + }); + for (key, value) in fields { + nbt[*key] = (*value).into(); + } + Some(json!({ + "processor_type": "minecraft:rule", + "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": input}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"Name": SPAWNER}, + "block_entity_modifier": {"type": "minecraft:append_static", "data": nbt}, + }], + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::legacy_structure_mods::data; + use crate::processors::{ProcessorData, carry}; + use crate::worldgen::{Upgrade, upgrade}; + + const NO_TAGS: BTreeMap> = BTreeMap::new(); + + #[test] + fn yungs_jigsaws_keep_their_rules() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "yungsapi:yung_jigsaw", "start_pool": "y:start", "size": 20, + "max_y": 60, "x_offset_in_chunk": 0, "max_distance_from_center": 80, + "enhanced_terrain_adaptation": {"type": "yungsapi:custom", "kernel_size": 24, + "kernel_distance": 24, "top": "carve", "bottom": "none"}}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); + assert_eq!( + s["horizon:enhanced_terrain_adaptation"], + json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", "bottom": "none", + "rigid_junctions": true, "inflate": true}) + ); + for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { + assert!(s.get(gone).is_none(), "{gone}"); + } + // Better Dungeons' small Nether dungeon is the same jigsaw. + let mut nether = json!({"type": "betterdungeons:small_nether_dungeon", + "start_pool": "betterdungeons:small_nether_dungeon", "size": 10, + "start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor", + "max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!(nether["horizon:yungsapi"], json!({})); + assert_eq!( + nether["horizon:enhanced_terrain_adaptation"], + json!({"kernel_size": 0, "kernel_distance": 0, "top": "none", "bottom": "none", + "rigid_junctions": true, "inflate": true}) + ); + assert_eq!( + nether["start_jigsaw_name"], + "betterdungeons:small_nether_dungeon_anchor" + ); + assert!(report.unsupported.is_empty()); + let mut pool = json!({"elements": [{"weight": 3, "element": { + "element_type": "yungsapi:yung_single_element", "location": "y:room", + "processors": "minecraft:empty", "projection": "rigid", + "name": "room", "max_count": 2, "min_required_depth": 1, "is_priority": true, + "ignore_bounds": false, "deadend_pool": "y:end", + "modifiers": [ + {"condition": {"type": "yungsapi:piece_in_range", "pieces": ["y:pillar"], + "above_range": 40}, + "target_selector": {"type": "yungsapi:self"}, + "actions": [{"type": "yungsapi:transform", "output": ["y:covered"], "x_offset": -1}, + {"type": "yungsapi:delay_generation"}, {"type": "yungsapi:spin"}]}, + {"condition": {"type": "yungsapi:always_true"}, + "target_selector": {"type": "yungsapi:all"}, "actions": []}], + "enhanced_terrain_adaptation": {"type": "yungsapi:carved_top_no_beard_small"}, + "condition": {"type": "yungsapi:all_of", "conditions": [ + {"type": "yungsapi:piece_in_horizontal_direction", "pieces": ["yungsapi:all"], + "range": 5, "rotation": "none"}, + {"type": "yungsapi:not", "condition": {"type": "yungsapi:mod_loaded", "modid": "create"}}, + {"type": "yungsapi:biome", "biomes": []}]}}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + let e = &pool["elements"][0]["element"]; + assert_eq!(e["element_type"], "minecraft:single_pool_element"); + assert_eq!(e["location"], "y:room"); + assert_eq!( + e["horizon:yungsapi"], + json!({"name": "room", "max_count": 2, "min_depth": 1, "priority": true, + "ignore_bounds": false, "condition": {"type": "all_of", "conditions": [ + {"type": "piece_in_horizontal_direction", "pieces": [], "range": 5, "rotation": "none"}, + {"type": "not", "condition": {"type": "false"}}, + {"type": "false"}]}, + "deadend_pool": "y:end", + "modifiers": [{"condition": {"type": "piece_in_range", "pieces": ["y:pillar"], + "horizontal_range": null, "above_range": 40, "below_range": null}, + "actions": [{"type": "transform", "output": ["y:covered"], "offset": [-1, 0, 0]}, + {"type": "delay_generation"}]}]}) + ); + assert!(e.get("deadend_pool").is_none() && e.get("modifiers").is_none()); + assert_eq!( + e["horizon:enhanced_terrain_adaptation"], + json!({"kernel_size": 12, "kernel_distance": 6, "top": "carve", "bottom": "none"}) + ); + assert_eq!( + report.rules_lost, + BTreeMap::from([ + ("yungsapi condition yungsapi:biome".into(), 1), + ("yungsapi modifier action yungsapi:spin".into(), 1), + ("yungsapi modifier target yungsapi:all".into(), 1), + ]) + ); + assert!(report.unsupported.is_empty()); + } + + #[test] + fn yungs_placements_keep_their_rules() { + let tags = BTreeMap::from([( + "bf:avoid".to_owned(), + vec!["minecraft:nether_complexes".to_owned()], + )]); + let mut report = Upgrade::default(); + let mut fortress = json!({"placement": {"type": "yungsapi:enhanced_random_spread", + "salt": 1, "spacing": 30, "separation": 20, + "enhanced_exclusion_zone": {"other_set": "#bf:avoid", "chunk_count": 10}}}); + assert!(upgrade("structure_set", &mut fortress, &mut report, &tags)); + assert_eq!( + fortress["placement"], + json!({"type": "minecraft:random_spread", "salt": 1, "spacing": 30, "separation": 20, + "horizon:exclusion_zone": {"other_sets": ["minecraft:nether_complexes"], "chunk_count": 10}}) + ); + let mut temple = json!({"placement": {"type": "betterdeserttemples:desert_temple", + "salt": 2, "spacing": 30, "separation": 20, + "exclusion_zone": {"other_set": "minecraft:villages", "chunk_count": 6}}}); + assert!(upgrade("structure_set", &mut temple, &mut report, &tags)); + assert_eq!(temple["placement"]["type"], "minecraft:random_spread"); + assert_eq!(temple["placement"]["exclusion_zone"]["chunk_count"], 6); + assert_eq!( + temple["placement"]["horizon:avoid_biomes"], + json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}) + ); + let mut stronghold = json!({"placement": {"type": "betterstrongholds:stronghold", + "salt": 3, "spacing": 85, "separation": 50, + "chunk_distance_to_first_ring": 80, "ring_chunk_thickness": 96}}); + assert!(upgrade( + "structure_set", + &mut stronghold, + &mut report, + &tags + )); + assert_eq!( + stronghold["placement"], + json!({"type": "minecraft:random_spread", "salt": 3, "spacing": 85, "separation": 50, + "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96}}) + ); + assert_eq!(report.mapped, 3); + assert!(report.unsupported.is_empty()); + // The vanilla counterpart is turned off only for a structure the game starts. + let mut ported = json!({"type": "minecraft:jigsaw"}); + assert!(disables("betterstrongholds:stronghold", &mut ported)); + assert_eq!(ported["horizon:disables"], json!(["minecraft:stronghold"])); + let mut java = json!({"type": "bettermineshafts:mineshaft"}); + assert!(!disables("bettermineshafts:mineshaft_oak", &mut java)); + let mut circle = json!({"type": "minecraft:jigsaw"}); + assert!(!disables("betterwitchhuts:witch_circle", &mut circle)); + } + + #[test] + fn yungs_spawners_become_rules() { + let mut pool = json!({"elements": [{"element": {"processors": {"processors": [ + {"processor_type": "betterdungeons:skeleton_mob_spawner_processor"}, + {"processor_type": "betterdeserttemples:bone_block_processor"}, + {"processor_type": "betterdungeons:small_nether_dungeon_mob_spawner_processor", + "spawner_mob": "minecraft:wither_skeleton"}, + {"processor_type": "betterdungeons:candle_processor"}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(carry("template_pool", &mut pool, &data(), &mut carried)); + let p = &pool["elements"][0]["element"]["processors"]["processors"]; + let rule = |i: usize| &p[i]["rules"][0]; + assert_eq!(rule(0)["input_predicate"]["block"], "minecraft:spawner"); + assert_eq!( + rule(0)["output_state"], + json!({"Name": "minecraft:spawner"}) + ); + let nbt = &rule(0)["block_entity_modifier"]["data"]; + assert_eq!( + ( + nbt["RequiredPlayerRange"].clone(), + nbt["MaxNearbyEntities"].clone() + ), + (json!(18), json!(8)) + ); + assert_eq!(nbt["MaxSpawnDelay"], 650); + assert_eq!( + nbt["SpawnPotentials"], + json!([{"data": {"entity": {"id": "minecraft:skeleton"}}, "weight": 1}]) + ); + // Bone blocks become bowless skeleton spawners with no potentials. + let bone = &rule(1)["block_entity_modifier"]["data"]; + assert_eq!(rule(1)["input_predicate"]["block"], "minecraft:bone_block"); + assert_eq!( + bone["SpawnData"], + json!({"entity": {"id": "minecraft:skeleton", "equipment": {}}}) + ); + assert_eq!(bone["SpawnPotentials"], json!([])); + let wither = &rule(2)["block_entity_modifier"]["data"]["SpawnData"]["entity"]; + assert_eq!( + wither["equipment"]["head"]["id"], + "minecraft:netherite_helmet" + ); + assert_eq!(wither["drop_chances"]["feet"], 0.0); + assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); + assert_eq!(carried.values().sum::(), 3); + } + + #[test] + fn desert_temple_placeholders_become_rules_and_picks() { + let mut list = json!({"processors": [ + {"processor_type": "betterdeserttemples:red_wool_processor"}, + {"processor_type": "betterdeserttemples:white_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:orange_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:pot_processor"}, + {"processor_type": "betterdeserttemples:quartz_pillar_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0]["rules"][0]["output_state"], + json!({"id": "minecraft:tnt"}) + ); + assert_eq!(p[1]["processor_type"], "horizon:pick"); + assert_eq!(p[1]["picks"][0]["below"], 0.4f32 as f64); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:air"); + let glass = &p[2]["picks"]; + assert_eq!(glass[0]["state"]["id"], "minecraft:suspicious_sand"); + assert_eq!( + glass[0]["nbt"]["LootTable"], + "minecraft:archaeology/desert_pyramid" + ); + assert_eq!(glass[3]["states"].as_array().unwrap().len(), 4); + assert_eq!(glass[3]["below"], 0.45f32 as f64); + assert_eq!(p[3]["default"]["lists"][0]["count"], 4); + // The pillar reads the world below: still Java, still dropped later. + assert_eq!( + p[4]["processor_type"], + "betterdeserttemples:quartz_pillar_processor" + ); + assert_eq!(carried.values().sum::(), 4); + } + + #[test] + fn small_dungeon_chests_are_capped() { + let mut list = json!({"processors": [ + {"processor_type": "betterdungeons:small_dungeon_chest_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let cap = &list["processors"][0]; + assert_eq!(cap["processor_type"], "horizon:count_cap"); + assert_eq!( + (cap["min"].as_u64(), cap["max"].as_u64()), + (Some(1), Some(2)) + ); + assert_eq!(cap["replacement"], json!({"id": "minecraft:cave_air"})); + } + + #[test] + fn ocean_monuments_become_the_games() { + let names = [ + "random_prismarine_slab_decoration_processor", + "random_dark_prismarine_slab_decoration_processor", + "sand_gravel_processor", + "random_oxidization_processor", + "structure_void_processor", + "air_processor", + "waterlog_processor", + "seagrass_processor", + "random_sponge_processor", + "leg_processor", + ]; + let processors: Vec = names + .iter() + .map(|n| json!({"processor_type": format!("betteroceanmonuments:{n}")})) + .chain([json!({"processor_type": "betterwitchhuts:fence_leg_processor"})]) + .collect(); + let mut list = json!({"processors": processors}); + let mut carried = BTreeMap::new(); + assert!(carry( + "processor_list", + &mut list, + &ProcessorData::default(), + &mut carried + )); + let p = list["processors"].as_array().unwrap(); + let types: Vec<&str> = p + .iter() + .map(|p| p["processor_type"].as_str().unwrap()) + .collect(); + let mut want = vec!["horizon:pick", "horizon:pick", "minecraft:rule"]; + want.extend(["horizon:pick"; 4]); + want.extend([ + "horizon:keep_world_block", + "horizon:flood_air", + "horizon:waterlog", + "minecraft:rule", + "horizon:pick", + "horizon:yung_pillar", + "horizon:yung_pillar", + ]); + assert_eq!(types, want); + assert_eq!(carried.values().sum::(), 11); + // Copper stairs keep their properties, each chance on a new float. + let stairs = &p[5]; + assert_eq!(stairs["block"], "minecraft:oxidized_cut_copper_stairs"); + assert_eq!( + stairs["picks"][1]["state"]["id"], + "minecraft:weathered_cut_copper_stairs" + ); + assert_eq!( + (stairs["redraw"].clone(), stairs["keep_properties"].clone()), + (json!(true), json!(true)) + ); + assert_eq!(p[0]["picks"][0]["state"]["properties"]["type"], "top"); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:water"); + assert_eq!( + p[12]["target_block_output"]["defaultBlockState"]["id"], + "minecraft:prismarine_bricks" + ); + assert_eq!(p[13]["keep_properties"], true); + } +} diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index f729b6c52..950413341 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -13,6 +13,7 @@ pub mod fetch; pub mod import; pub mod inventory; pub mod jar; +pub(crate) mod legacy_structure_mods; pub mod modrinth; pub mod oracle; pub mod pipeline; diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index e6c0fe7d8..f182bee7b 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -5,27 +5,18 @@ //! processors pick a mob from a weighted list for each spawner. They become //! `horizon:spawner_mobs` (`horizon_world::worldgen::structure::processor`), //! with Repurposed's `rs_spawners` list written in. -//! - YUNG's Better Dungeons and Better Desert Temples turn a spawner or a -//! placeholder block into a spawner of a fixed mob. That is vanilla's `rule` -//! processor with an `append_static` block entity. //! - Moog's vanilla loot swap only acts when its mod's "replace vanilla" //! preset is on; one that ships off is a no-op and is taken out. -//! - Lithostitched's `reference` runs other processor lists in turn: their -//! processors are written in its place (Choice Theorem's Overhauled -//! Villages builds most of its lists so). Its `apply_random` and -//! `condition` become the game's `horizon:apply_random` and -//! `horizon:condition`, with the lists inside them carried the same way, -//! and its `set_block` (simple or weighted states) `horizon:set_block`. //! - Repurposed Structures' mineshaft sky view becomes the game's //! `horizon:mineshaft_sky_view`. -//! - Choice Theorem's Overhauled Village's `modular_compat` runs another -//! list only when the mod it names is loaded: that list is written in its -//! place when the mod is ported along, and it is taken out (a no-op, as in -//! the mod) when it is not. +//! +//! The processors of YUNG's mods, Lithostitched and Choice Theorem's Overhauled +//! Village are carried by `legacy_structure_mods`, called from [`carry`]. //! //! What is not here is taken out of its list later and counted //! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an //! `equipment` map, not 1.21.1's `HandItems` and `ArmorItems`). +use crate::legacy_structure_mods::{ctov, lithostitched, yung}; use serde_json::{Value, json}; use std::{ collections::{BTreeMap, BTreeSet}, @@ -48,30 +39,10 @@ pub struct ProcessorData { pub compat_loaded: BTreeSet, } -/// Choice Theorem's Overhauled Village's processor that runs the list -/// `reference` when mod `modid` is loaded (ModularCompatProcessor). -const MODULAR_COMPAT: &str = "ctov:modular_compat"; - impl ProcessorData { /// Notes which mods its compat processors name are `loaded`. pub fn mark_loaded(&mut self, loaded: &dyn Fn(&str) -> bool) { - fn walk(v: &Value, out: &mut BTreeSet) { - match v { - Value::Object(o) => { - if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) { - if let Some(id) = o.get("modid").and_then(Value::as_str) { - out.insert(id.to_owned()); - } - } - o.values().for_each(|v| walk(v, out)); - } - Value::Array(a) => a.iter().for_each(|v| walk(v, out)), - _ => {} - } - } - let mut named = BTreeSet::new(); - self.lists.values().for_each(|l| walk(l, &mut named)); - self.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect(); + ctov::mark_loaded(self, loaded); } pub fn read(zip: &mut zip::ZipArchive) -> Self { @@ -187,7 +158,7 @@ pub fn carry( /// The processors of one list carried: references written in, then each /// one with a data form replaced by it. Whether anything changed. -fn carry_all( +pub(crate) fn carry_all( list: Vec, data: &ProcessorData, carried: &mut BTreeMap, @@ -202,18 +173,18 @@ fn carry_at( carried: &mut BTreeMap, depth: usize, ) -> (Vec, bool) { - let (expanded, mut changed) = references(list, data, carried, 0); + let (expanded, mut changed) = lithostitched::expand_references(list, data, carried); let mut out = Vec::with_capacity(expanded.len()); for p in expanded { let kind = p["processor_type"].as_str().unwrap_or_default().to_owned(); - let replacement = match kind.as_str() { - "lithostitched:apply_random" => apply_random(&p, data, carried).map(|p| vec![p]), - "lithostitched:condition" => condition(&p, data, carried).map(|p| vec![p]), - _ => match pillar_type(&kind) { + // Lithostitched's and YUNG's processors are carried apart from this + // code (`legacy_structure_mods`). + let replacement = lithostitched::processor(&kind, &p, data, carried).or_else(|| { + match pillar_type(&kind).or_else(|| yung::pillar_type(&kind)) { Some(to) => Some(vec![pillar(&p, to, data, carried, depth)]), - None => as_data(&kind, &p, data), - }, - }; + None => as_data(&kind, &p, data).or_else(|| yung::processor(&kind, &p)), + } + }); match replacement { Some(replacement) => { *carried.entry(kind).or_default() += 1; @@ -237,10 +208,6 @@ fn pillar_type(kind: &str) -> Option<&'static str> { "repurposed_structures:close_off_fluid_sources_processor" | "moogs_structures:close_off_fluid_sources_processor" => "horizon:close_off_fluid_sources", "repurposed_structures:close_off_air_sources_processor" => "horizon:close_off_air_sources", - "betterfortresses:pillar_processor" | "betterjungletemples:pillar_processor" => { - "horizon:yung_pillar" - } - "betterfortresses:stair_pillar_processor" => "horizon:stair_pillar", _ => return None, }) } @@ -248,8 +215,7 @@ fn pillar_type(kind: &str) -> Option<&'static str> { /// A pillar processor as the game's `to`. Its `pillar_processor_list` /// (which runs on each block of the column; Repurposed's often names the /// list it is in) is written in, carried; the pillars inside that copy lose -/// theirs, as a column's blocks are never the mods' triggers. Better -/// Fortresses' stair supports get the blocks its Java code names. +/// theirs, as a column's blocks are never the mods' triggers. fn pillar( p: &Value, to: &str, @@ -257,13 +223,6 @@ fn pillar( carried: &mut BTreeMap, depth: usize, ) -> Value { - if to == "horizon:stair_pillar" { - return json!({"processor_type": to, - "blocks": {"minecraft:stone_brick_stairs": "minecraft:red_nether_brick_stairs", - "minecraft:purpur_stairs": "minecraft:red_nether_bricks"}, - "front": "minecraft:red_nether_brick_stairs", - "pillar": "minecraft:red_nether_bricks"}); - } let mut out = p.clone(); out["processor_type"] = to.into(); let Some(o) = out.as_object_mut() else { @@ -284,108 +243,6 @@ fn pillar( out } -/// A processor list inside a carried processor: an id stays (the game reads -/// that file, carried on its own); an inline one is carried here. -fn nested(list: &Value, data: &ProcessorData, carried: &mut BTreeMap) -> Value { - let mut list = list.clone(); - if let Some(ps) = processors(&mut list) { - *ps = carry_all(std::mem::take(ps), data, carried).0; - } - list -} - -/// Lithostitched's `apply_random` as `horizon:apply_random`: its weighted -/// lists, or its set of lists at weight 1. A tag is not carried. -fn apply_random( - p: &Value, - data: &ProcessorData, - carried: &mut BTreeMap, -) -> Option { - let lists = &p["processor_lists"]; - let weighted = lists.as_array().is_some_and(|a| { - a.iter() - .all(|e| e.get("weight").is_some() && e.get("data").is_some()) - }); - let entries: Vec<(Value, Value)> = if weighted { - lists - .as_array()? - .iter() - .map(|e| (e["weight"].clone(), e["data"].clone())) - .collect() - } else { - match lists { - Value::String(id) if !id.starts_with('#') => vec![(1.into(), lists.clone())], - Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => { - vec![(1.into(), lists.clone())] - } - Value::Array(a) - if a.iter() - .all(|x| x.as_str().is_some_and(|s| !s.starts_with('#')) || x.is_object()) => - { - a.iter().map(|x| (1.into(), x.clone())).collect() - } - Value::Object(_) => vec![(1.into(), lists.clone())], - _ => return None, - } - }; - let lists: Vec = entries - .into_iter() - .map(|(weight, list)| json!({"weight": weight, "data": nested(&list, data, carried)})) - .collect(); - let mut out = json!({"processor_type": "horizon:apply_random", "processor_lists": lists}); - if let Some(mode) = p.get("mode") { - out["mode"] = mode.clone(); - } - Some(out) -} - -/// Lithostitched's `condition` as `horizon:condition`, when the game runs -/// every condition in it (true, all_of, any_of, not, random_chance, -/// matching_blocks with plain property values); else it stays Java. -fn condition( - p: &Value, - data: &ProcessorData, - carried: &mut BTreeMap, -) -> Option { - fn runs(c: &Value) -> bool { - if let Some(all) = c.as_array() { - return all.iter().all(runs); - } - let kind = c["type"].as_str().unwrap_or_default(); - match kind.strip_prefix("lithostitched:").unwrap_or(kind) { - "true" | "random_chance" => true, - "all_of" | "any_of" => c["conditions"] - .as_array() - .is_some_and(|a| a.iter().all(runs)), - "not" => runs(&c["condition"]), - "matching_blocks" => c.get("properties").is_none_or(|p| { - p.as_object() - .is_some_and(|o| o.values().all(Value::is_string)) - }), - _ => false, - } - } - if !runs(&p["if_true"]) { - return None; - } - // One processor or a list of them. - let mut branch = |key: &str| -> Value { - let list = match p.get(key) { - None => Vec::new(), - Some(Value::Array(a)) => a.clone(), - Some(one) => vec![one.clone()], - }; - carry_all(list, data, carried).0.into() - }; - let (then, otherwise) = (branch("then"), branch("else")); - let mut out = json!({"processor_type": "horizon:condition", "if_true": p["if_true"], - "then": then, "else": otherwise}); - if let Some(mode) = p.get("random_mode") { - out["random_mode"] = mode.clone(); - } - Some(out) -} - /// Repurposed Structures' rule tests and the game's types that run them /// (`horizon_world::worldgen`'s `rule_test` and `structure::processor`). const RULE_TESTS: [(&str, &str); 3] = [ @@ -429,48 +286,9 @@ pub fn rule_tests(kind: &str, v: &mut Value, carried: &mut BTreeMap, - data: &ProcessorData, - carried: &mut BTreeMap, - depth: usize, -) -> (Vec, bool) { - let mut out = Vec::with_capacity(list.len()); - let mut changed = false; - for p in list { - if p["processor_type"] == MODULAR_COMPAT && depth < 8 { - *carried.entry(MODULAR_COMPAT.into()).or_default() += 1; - changed = true; - let loaded = p["modid"] - .as_str() - .is_some_and(|m| data.compat_loaded.contains(m)); - if let Some(inner) = loaded.then(|| referenced(&p["reference"], data)).flatten() { - out.extend(references(inner, data, carried, depth + 1).0); - } - continue; - } - let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) - .then(|| referenced(&p["processor_lists"], data)) - .flatten(); - match named { - Some(inner) => { - *carried.entry("lithostitched:reference".into()).or_default() += 1; - out.extend(references(inner, data, carried, depth + 1).0); - changed = true; - } - None => out.push(p), - } - } - (out, changed) -} - /// The processors of the lists a reference names: an id, an inline list, or /// a list of either. -fn referenced(lists: &Value, data: &ProcessorData) -> Option> { +pub(crate) fn referenced(lists: &Value, data: &ProcessorData) -> Option> { let one = |l: &Value| -> Option> { let mut list = match l { Value::String(id) if !id.starts_with('#') => { @@ -497,7 +315,7 @@ fn referenced(lists: &Value, data: &ProcessorData) -> Option> { /// The data form of a Java processor: the processors to put in its place /// (none for a no-op), or `None` when it has none. fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { - let (ns, _) = kind.split_once(':')?; + kind.split_once(':')?; Some(match kind { // Its structure voids keep the world's block, as vanilla's // block_ignore does (the templates hold them; vanilla places them). @@ -593,171 +411,6 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { |s| config(s.get("ominous") == Some(&"true")), )] } - _ if ns == "betterdeserttemples" - && let Some(processor) = desert_temple(kind) => - { - vec![processor] - } - "lithostitched:block_swap" => { - // The same map; the game's swap keeps the properties both have. - p["blocks"].as_object()?; - vec![json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]})] - } - "lithostitched:set_block" => { - // A simple or weighted state provider, the block entity left as - // it is. - let provider = p["state_provider"]["type"].as_str()?; - let modifier = p["block_entity_modifier"]["type"].as_str(); - let plain = - modifier.is_none_or(|m| m.trim_start_matches("minecraft:") == "passthrough"); - if !plain - || !matches!( - provider, - "minecraft:simple_state_provider" | "minecraft:weighted_state_provider" - ) - { - return None; - } - let mut out = p.clone(); - out["processor_type"] = "horizon:set_block".into(); - if let Some(o) = out.as_object_mut() { - o.remove("block_entity_modifier"); - } - vec![out] - } - "betterdungeons:small_dungeon_chest_processor" => { - // Its config's defaults: one chest at least, two at most, a - // fifth of the others kept until then; ChestBlock covers both. - vec![json!({"processor_type": "horizon:count_cap", - "blocks": ["minecraft:chest", "minecraft:trapped_chest"], - "min": 1, "max": 2, "chance": 0.2f32 as f64, - "replacement": block("minecraft:cave_air")})] - } - "betterwitchhuts:leg_processor" => vec![yung_leg( - "minecraft:brown_stained_glass", - json!({"id": "minecraft:oak_log", "properties": {"axis": "y"}}), - false, - )], - "betterwitchhuts:fence_leg_processor" => vec![yung_leg( - "minecraft:crimson_fence", - block("minecraft:oak_fence"), - true, - )], - _ if ns == "betteroceanmonuments" => ocean_monument(kind)?, - _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], - _ => return None, - }) -} - -/// YUNG's leg processors (Better Ocean Monuments, Better Witch Huts): a -/// placeholder block becomes `state` and a column of it runs down through -/// air and fluids: the game's `horizon:yung_pillar` with fixed states, and -/// the placeholder's properties kept for the fence legs. -fn yung_leg(target: &str, state: Value, keep_properties: bool) -> Value { - let fixed = json!({"entries": [], "defaultBlockState": state}); - json!({"processor_type": "horizon:yung_pillar", "target_block": block(target), - "target_block_output": fixed, "pillar_states": fixed, - "keep_properties": keep_properties}) -} - -/// Better Ocean Monuments' processors (no fields; what they do is in their -/// Java code): placeholder blocks as vanilla's `rule` or the game's -/// `horizon:pick` (a new `nextFloat` for each chance, as the mod draws), -/// and its sea-level ones as the game's `horizon:flood_air`, -/// `horizon:waterlog` and `horizon:keep_world_block`. -fn ocean_monument(kind: &str) -> Option> { - let rule = |rules: &[(&str, Value)]| { - let rules: Vec = rules - .iter() - .map(|(from, to)| { - json!({"input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, - "location_predicate": {"predicate_type": "minecraft:always_true"}, - "output_state": to}) - }) - .collect(); - json!({"processor_type": "minecraft:rule", "rules": rules}) - }; - let state = |id: &str, props: Value| json!({"id": id, "properties": props}); - let pick = |from: &str, picks: Vec<(f32, Value)>, default: Value, keep: bool| { - let picks: Vec = picks - .into_iter() - .map(|(below, state)| json!({"below": below as f64, "state": state})) - .collect(); - json!({"processor_type": "horizon:pick", "block": from, "picks": picks, - "default": {"state": default}, "redraw": true, "keep_properties": keep}) - }; - let slabs = |from: &str, slab: &str, otherwise: &str| { - let wet = |t: &str| state(slab, json!({"type": t, "waterlogged": "true"})); - pick( - from, - vec![(0.4, wet("top")), (0.8, wet("bottom"))], - block(otherwise), - false, - ) - }; - // Exposed below 0.1, else weathered below a new 0.3, else oxidized, - // with the placeholder's properties for the stairs and slabs. - let copper = |kind: &str| { - let id = |age: &str| block(&format!("minecraft:{age}{kind}")); - pick( - &format!("minecraft:oxidized_{kind}"), - vec![(0.1, id("exposed_")), (0.3, id("weathered_"))], - id("oxidized_"), - true, - ) - }; - Some(match kind.strip_prefix("betteroceanmonuments:")? { - "random_prismarine_slab_decoration_processor" => vec![slabs( - "minecraft:lime_concrete", - "minecraft:prismarine_slab", - "minecraft:air", - )], - "random_dark_prismarine_slab_decoration_processor" => vec![slabs( - "minecraft:blue_concrete", - "minecraft:dark_prismarine_slab", - "minecraft:water", - )], - "sand_gravel_processor" => { - vec![rule(&[( - "minecraft:yellow_stained_glass", - block("minecraft:gravel"), - )])] - } - "random_oxidization_processor" => [ - "copper", - "cut_copper", - "cut_copper_stairs", - "cut_copper_slab", - ] - .into_iter() - .map(copper) - .collect(), - "structure_void_processor" => vec![json!({"processor_type": "horizon:keep_world_block", - "blocks": ["minecraft:purpur_slab", "minecraft:brown_wool"]})], - "air_processor" => vec![json!({"processor_type": "horizon:flood_air"})], - "waterlog_processor" => vec![json!({"processor_type": "horizon:waterlog"})], - "seagrass_processor" => vec![rule(&[ - ( - "minecraft:red_sandstone_slab", - state("minecraft:tall_seagrass", json!({"half": "lower"})), - ), - ( - "minecraft:end_stone_brick_slab", - state("minecraft:tall_seagrass", json!({"half": "upper"})), - ), - ("minecraft:brick_slab", block("minecraft:seagrass")), - ])], - "random_sponge_processor" => vec![pick( - "minecraft:orange_stained_glass", - vec![(0.75, block("minecraft:wet_sponge"))], - block("minecraft:water"), - false, - )], - "leg_processor" => vec![yung_leg( - "minecraft:blue_stained_glass", - block("minecraft:prismarine_bricks"), - false, - )], _ => return None, }) } @@ -885,110 +538,6 @@ pub fn upgrade_trial_spawner(config: &mut Value) -> bool { changed } -/// A block state as 26.3 writes it. -fn block(id: &str) -> Value { - json!({"id": id}) -} - -/// Better Desert Temples' placeholder blocks (glass, concrete and wool in -/// the templates) as the mod's processors turn them: the fixed ones as -/// vanilla's `rule`, the random ones as the game's `horizon:pick`, with the -/// mod's bounds on one `nextFloat` (YUNG's BlockStateRandomizer adds its -/// chances up in floats). The ones that read or change the world around -/// (pillars, Diorite's waterlogging) stay dropped. -fn desert_temple(kind: &str) -> Option { - let swap = |from: &str, to: &str| { - json!({"processor_type": "minecraft:rule", "rules": [{ - "input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, - "location_predicate": {"predicate_type": "minecraft:always_true"}, - "output_state": block(to)}]}) - }; - let pick = |from: &str, picks: Vec, default: Value| json!({"processor_type": "horizon:pick", "block": from, "picks": picks, "default": default}); - // YUNG's BlockStateRandomizer: an entry wins below the sum of the - // chances so far, summed as floats. - let randomizer = |entries: &[(f32, &str)]| { - let mut bottom = 0f32; - entries - .iter() - .map(|(chance, id)| { - bottom += chance; - json!({"below": bottom as f64, "state": block(id)}) - }) - .collect::>() - }; - let at = |below: f32, id: &str| json!({"below": below as f64, "state": block(id)}); - // Sandstone stairs, upside down, facing Plane.HORIZONTAL.getRandomDirection. - let stairs = || { - let states: Vec = ["north", "east", "south", "west"] - .iter() - .map(|facing| { - json!({"id": "minecraft:sandstone_stairs", "properties": { - "facing": facing, "half": "top", "shape": "straight", "waterlogged": "false"}}) - }) - .collect(); - json!({"states": states}) - }; - Some(match kind.strip_prefix("betterdeserttemples:")? { - "blue_concrete_processor" => swap("minecraft:blue_concrete", "minecraft:blue_terracotta"), - "yellow_concrete_processor" => { - swap("minecraft:yellow_concrete", "minecraft:yellow_terracotta") - } - "red_wool_processor" => swap("minecraft:red_wool", "minecraft:tnt"), - "white_stained_glass_processor" => pick( - "minecraft:white_stained_glass", - randomizer(&[(0.4, "minecraft:cobweb")]), - json!({"state": block("minecraft:air")}), - ), - "polished_diorite_processor" => pick( - "minecraft:polished_diorite", - randomizer(&[(0.6, "minecraft:cut_sandstone")]), - json!({"state": block("minecraft:sandstone")}), - ), - "orange_stained_glass_processor" => { - let mut sus = at(0.01, "minecraft:suspicious_sand"); - sus["nbt"] = json!({"LootTable": "minecraft:archaeology/desert_pyramid"}); - let mut stairs = stairs(); - stairs["below"] = (0.45f32 as f64).into(); - pick( - "minecraft:orange_stained_glass", - vec![ - sus, - at(0.1, "minecraft:sand"), - at(0.2, "minecraft:sandstone"), - stairs, - ], - json!({"state": block("minecraft:cut_sandstone")}), - ) - } - "red_stained_glass_processor" => pick( - "minecraft:red_stained_glass", - vec![at(0.3, "minecraft:sand"), at(0.75, "minecraft:sandstone")], - stairs(), - ), - "pot_processor" => { - // Four sherds, one float each; the pot back to its default state. - let values: Vec = [ - (0.05f32, "archer"), - (0.1, "miner"), - (0.15, "prize"), - (0.2, "skull"), - ] - .iter() - .map(|(below, sherd)| { - json!({"below": *below as f64, "value": format!("minecraft:{sherd}_pottery_sherd")}) - }) - .collect(); - pick( - "minecraft:decorated_pot", - Vec::new(), - json!({"state": block("minecraft:decorated_pot"), "lists": [{ - "key": "sherds", "count": 4, "values": values, "default": "minecraft:brick"}]}), - ) - } - _ => return None, - }) -} - /// [`as_data`]'s `horizon:spawner_mobs` for the mods' spawner randomizing /// processors, whose fields have the same names and defaults. fn spawner_mobs(p: &Value, mobs: Vec, rules: Option) -> Value { @@ -1046,135 +595,6 @@ fn repurposed_light(p: &Value) -> Option> { Some(Some(rules)) } -/// An item as 26.3 saves it. -fn item(id: &str) -> Value { - json!({"id": format!("minecraft:{id}"), "count": 1}) -} - -/// YUNG's processors that make a spawner of a fixed mob (YUNG's API's -/// `MobSpawnerData`), as vanilla's `rule`: every `input` block becomes a -/// spawner with that NBT. -fn yung_spawner(kind: &str, p: &Value) -> Option { - const SPAWNER: &str = "minecraft:spawner"; - // (input block, mob, fields other than the defaults, whether the mob is - // also the only potential, its equipment) - let (input, mob, fields, potential, equipment): (_, _, &[(&str, i64)], _, _) = match kind { - "betterdungeons:mob_spawner_processor" => { - (SPAWNER, p["spawner_mob"].as_str()?, &[], true, None) - } - "betterdungeons:zombie_mob_spawner_processor" => ( - SPAWNER, - "minecraft:zombie", - &[("MaxNearbyEntities", 8)], - true, - None, - ), - "betterdungeons:skeleton_mob_spawner_processor" => ( - SPAWNER, - "minecraft:skeleton", - &[ - ("RequiredPlayerRange", 18), - ("MaxNearbyEntities", 8), - ("MaxSpawnDelay", 650), - ], - true, - None, - ), - "betterdungeons:small_nether_dungeon_mob_spawner_processor" => { - let mob = p["spawner_mob"].as_str()?; - // Wither skeletons get netherite armor that never drops and a - // stone sword (with the mod's default config, they and blazes - // keep their loot). - let armor = (mob == "minecraft:wither_skeleton").then(|| { - json!({ - "equipment": { - "feet": item("netherite_boots"), - "legs": item("netherite_leggings"), - "chest": item("netherite_chestplate"), - "head": item("netherite_helmet"), - "mainhand": item("stone_sword"), - }, - "drop_chances": {"feet": 0.0, "legs": 0.0, "chest": 0.0, "head": 0.0}, - }) - }); - (SPAWNER, mob, &[], true, armor) - } - "betterdungeons:zombie_tombstone_spawner_processor" => ( - "minecraft:black_stained_glass", - "minecraft:skeleton", - &[], - false, - Some(json!({"equipment": {"mainhand": item("iron_sword")}})), - ), - "betterdeserttemples:gravel_processor" => ( - "minecraft:gravel", - "minecraft:husk", - &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], - false, - None, - ), - // An empty hand list in 1.21.1: the skeletons spawn without a bow, - // since a spawn entry with more than its id is not finalized. - "betterdeserttemples:bone_block_processor" => ( - "minecraft:bone_block", - "minecraft:skeleton", - &[("RequiredPlayerRange", 32)], - false, - Some(json!({"equipment": {}})), - ), - "betterdeserttemples:infested_cracked_stone_bricks_processor" => ( - "minecraft:infested_cracked_stone_bricks", - "minecraft:silverfish", - &[("RequiredPlayerRange", 24)], - false, - None, - ), - // 1.21.1 ignores the items' old `Count` and `tag` (the shield's - // pattern, the boots' dye): plain items. - "betterdeserttemples:yellow_wool_processor" => ( - "minecraft:yellow_wool", - "minecraft:husk", - &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], - false, - Some(json!({"equipment": { - "mainhand": item("golden_sword"), - "offhand": item("shield"), - "feet": item("leather_boots"), - "legs": item("leather_leggings"), - "chest": item("golden_chestplate"), - "head": item("chainmail_helmet"), - }})), - ), - _ => return None, - }; - let mut entity = json!({"id": mob}); - if let Some(Value::Object(extra)) = equipment { - entity.as_object_mut()?.extend(extra); - } - let potentials = match potential { - true => json!([{"data": {"entity": entity.clone()}, "weight": 1}]), - false => json!([]), - }; - let mut nbt = json!({ - "Delay": 20, "MinSpawnDelay": 200, "MaxSpawnDelay": 800, "SpawnCount": 4, - "MaxNearbyEntities": 6, "RequiredPlayerRange": 16, "SpawnRange": 4, - "SpawnData": {"entity": entity}, - "SpawnPotentials": potentials, - }); - for (key, value) in fields { - nbt[*key] = (*value).into(); - } - Some(json!({ - "processor_type": "minecraft:rule", - "rules": [{ - "input_predicate": {"predicate_type": "minecraft:block_match", "block": input}, - "location_predicate": {"predicate_type": "minecraft:always_true"}, - "output_state": {"Name": SPAWNER}, - "block_entity_modifier": {"type": "minecraft:append_static", "data": nbt}, - }], - })) -} - #[cfg(test)] mod tests { use super::*; @@ -1246,54 +666,6 @@ mod tests { ); } - #[test] - fn yungs_spawners_become_rules() { - let mut pool = json!({"elements": [{"element": {"processors": {"processors": [ - {"processor_type": "betterdungeons:skeleton_mob_spawner_processor"}, - {"processor_type": "betterdeserttemples:bone_block_processor"}, - {"processor_type": "betterdungeons:small_nether_dungeon_mob_spawner_processor", - "spawner_mob": "minecraft:wither_skeleton"}, - {"processor_type": "betterdungeons:candle_processor"}]}}}]}); - let mut carried = BTreeMap::new(); - assert!(carry("template_pool", &mut pool, &data(), &mut carried)); - let p = &pool["elements"][0]["element"]["processors"]["processors"]; - let rule = |i: usize| &p[i]["rules"][0]; - assert_eq!(rule(0)["input_predicate"]["block"], "minecraft:spawner"); - assert_eq!( - rule(0)["output_state"], - json!({"Name": "minecraft:spawner"}) - ); - let nbt = &rule(0)["block_entity_modifier"]["data"]; - assert_eq!( - ( - nbt["RequiredPlayerRange"].clone(), - nbt["MaxNearbyEntities"].clone() - ), - (json!(18), json!(8)) - ); - assert_eq!(nbt["MaxSpawnDelay"], 650); - assert_eq!( - nbt["SpawnPotentials"], - json!([{"data": {"entity": {"id": "minecraft:skeleton"}}, "weight": 1}]) - ); - // Bone blocks become bowless skeleton spawners with no potentials. - let bone = &rule(1)["block_entity_modifier"]["data"]; - assert_eq!(rule(1)["input_predicate"]["block"], "minecraft:bone_block"); - assert_eq!( - bone["SpawnData"], - json!({"entity": {"id": "minecraft:skeleton", "equipment": {}}}) - ); - assert_eq!(bone["SpawnPotentials"], json!([])); - let wither = &rule(2)["block_entity_modifier"]["data"]["SpawnData"]["entity"]; - assert_eq!( - wither["equipment"]["head"]["id"], - "minecraft:netherite_helmet" - ); - assert_eq!(wither["drop_chances"]["feet"], 0.0); - assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); - assert_eq!(carried.values().sum::(), 3); - } - #[test] fn trial_spawners_and_vaults_drop_their_saved_state() { let mut list = json!({"processors": [ @@ -1355,41 +727,6 @@ mod tests { assert!(!upgrade_trial_spawner(&mut config)); } - #[test] - fn desert_temple_placeholders_become_rules_and_picks() { - let mut list = json!({"processors": [ - {"processor_type": "betterdeserttemples:red_wool_processor"}, - {"processor_type": "betterdeserttemples:white_stained_glass_processor"}, - {"processor_type": "betterdeserttemples:orange_stained_glass_processor"}, - {"processor_type": "betterdeserttemples:pot_processor"}, - {"processor_type": "betterdeserttemples:quartz_pillar_processor"}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data(), &mut carried)); - let p = list["processors"].as_array().unwrap(); - assert_eq!( - p[0]["rules"][0]["output_state"], - json!({"id": "minecraft:tnt"}) - ); - assert_eq!(p[1]["processor_type"], "horizon:pick"); - assert_eq!(p[1]["picks"][0]["below"], 0.4f32 as f64); - assert_eq!(p[1]["default"]["state"]["id"], "minecraft:air"); - let glass = &p[2]["picks"]; - assert_eq!(glass[0]["state"]["id"], "minecraft:suspicious_sand"); - assert_eq!( - glass[0]["nbt"]["LootTable"], - "minecraft:archaeology/desert_pyramid" - ); - assert_eq!(glass[3]["states"].as_array().unwrap().len(), 4); - assert_eq!(glass[3]["below"], 0.45f32 as f64); - assert_eq!(p[3]["default"]["lists"][0]["count"], 4); - // The pillar reads the world below: still Java, still dropped later. - assert_eq!( - p[4]["processor_type"], - "betterdeserttemples:quartz_pillar_processor" - ); - assert_eq!(carried.values().sum::(), 4); - } - #[test] fn repurposed_waterlogging_follows_the_world() { let mut list = json!({"processors": [{"processor_type": @@ -1409,143 +746,6 @@ mod tests { ); } - #[test] - fn small_dungeon_chests_are_capped() { - let mut list = json!({"processors": [ - {"processor_type": "betterdungeons:small_dungeon_chest_processor"}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data(), &mut carried)); - let cap = &list["processors"][0]; - assert_eq!(cap["processor_type"], "horizon:count_cap"); - assert_eq!( - (cap["min"].as_u64(), cap["max"].as_u64()), - (Some(1), Some(2)) - ); - assert_eq!(cap["replacement"], json!({"id": "minecraft:cave_air"})); - } - - #[test] - fn lithostitched_block_swaps_become_the_games() { - let mut list = json!({"processors": [ - {"processor_type": "lithostitched:block_swap", - "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}, - {"processor_type": "lithostitched:block_swap", "blocks": []}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data(), &mut carried)); - let p = list["processors"].as_array().unwrap(); - assert_eq!( - p[0], - json!({"processor_type": "horizon:block_swap", - "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}) - ); - // A map that is not one stays Java (dropped later). - assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); - } - - #[test] - fn modular_compat_runs_its_list_only_with_its_mod() { - let mut data = ProcessorData::default(); - let swap = json!({"processor_type": "minecraft:rule", "rules": []}); - data.lists - .insert("v:house_ns".into(), json!({"processors": [swap.clone()]})); - let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"}); - let gravity = json!({"processor_type": "minecraft:gravity"}); - data.lists.insert( - "v:house".into(), - json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}), - ); - data.mark_loaded(&|m| m == "ns"); - assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()])); - let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut v, &data, &mut carried)); - assert_eq!(v, json!({"processors": [swap, gravity]})); - assert_eq!(carried["ctov:modular_compat"], 2); - } - - #[test] - fn lithostitched_references_are_written_in() { - let mut data = data(); - let gravity = json!({"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}); - data.lists - .insert("v:road".into(), json!({"processors": [gravity.clone()]})); - data.lists.insert( - "v:house".into(), - json!({"processors": [ - {"processor_type": "lithostitched:reference", "processor_lists": "v:road"}, - {"processor_type": "lithostitched:block_swap", "blocks": {"minecraft:dirt": "minecraft:grass_block"}}]}), - ); - let mut list = json!({"processors": [ - {"processor_type": "lithostitched:reference", "processor_lists": ["v:house", "v:road"]}, - {"processor_type": "lithostitched:reference", "processor_lists": "#v:roads"}, - {"processor_type": "lithostitched:reference", "processor_lists": ["v:nowhere"]}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data, &mut carried)); - let p = list["processors"].as_array().unwrap(); - // House (its own reference to road first, then its swap), then road; - // the swap inside is carried too. - assert_eq!(p[0], gravity); - assert_eq!(p[1]["processor_type"], "horizon:block_swap"); - assert_eq!(p[2], gravity); - // A tag or a list the mod lacks stays, to be dropped. - assert_eq!(p[3]["processor_lists"], "#v:roads"); - assert_eq!(p[4]["processor_lists"], json!(["v:nowhere"])); - assert_eq!(carried["lithostitched:reference"], 2); - } - - #[test] - fn lithostitched_random_and_condition_become_the_games() { - let mut data = data(); - let swap = json!({"processor_type": "lithostitched:block_swap", - "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); - data.lists - .insert("v:green".into(), json!({"processors": [swap.clone()]})); - let mut list = json!({"processors": [ - {"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [ - {"weight": 3, "data": "minecraft:empty"}, - {"weight": 1, "data": {"processors": [ - {"processor_type": "lithostitched:reference", "processor_lists": "v:green"}, - {"processor_type": "v:java"}]}}]}, - {"processor_type": "lithostitched:apply_random", "mode": "per_block", - "processor_lists": ["v:green", "v:red"]}, - {"processor_type": "lithostitched:apply_random", "mode": "per_block", - "processor_lists": "#v:colours"}, - {"processor_type": "lithostitched:condition", - "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], - "then": swap, "else": {"processor_type": "lithostitched:set_block", "state_provider": - {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}}, - {"processor_type": "lithostitched:condition", - "if_true": {"type": "lithostitched:matching_biomes", "biomes": "#c:is_cold"}, - "then": []}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data, &mut carried)); - let p = list["processors"].as_array().unwrap(); - let green = json!({"processor_type": "horizon:block_swap", - "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); - // Inline lists are carried; Java left in them is dropped later. - assert_eq!( - p[0], - json!({"processor_type": "horizon:apply_random", "mode": "per_piece", "processor_lists": [ - {"weight": 3, "data": "minecraft:empty"}, - {"weight": 1, "data": {"processors": [green.clone(), {"processor_type": "v:java"}]}}]}) - ); - assert_eq!( - p[1]["processor_lists"], - json!([{"weight": 1, "data": "v:green"}, {"weight": 1, "data": "v:red"}]) - ); - assert_eq!(p[2]["processor_type"], "lithostitched:apply_random"); - assert_eq!( - p[3], - json!({"processor_type": "horizon:condition", - "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], - "then": [green], "else": [{"processor_type": "horizon:set_block", "state_provider": - {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}]}) - ); - assert_eq!(p[4]["processor_type"], "lithostitched:condition"); - assert_eq!(carried["lithostitched:apply_random"], 2); - assert_eq!(carried["lithostitched:condition"], 1); - } - #[test] fn repurposed_rule_tests_become_the_games() { let rule = |input: Value, position: Value| { @@ -1600,71 +800,6 @@ mod tests { )); } - #[test] - fn ocean_monuments_become_the_games() { - let names = [ - "random_prismarine_slab_decoration_processor", - "random_dark_prismarine_slab_decoration_processor", - "sand_gravel_processor", - "random_oxidization_processor", - "structure_void_processor", - "air_processor", - "waterlog_processor", - "seagrass_processor", - "random_sponge_processor", - "leg_processor", - ]; - let processors: Vec = names - .iter() - .map(|n| json!({"processor_type": format!("betteroceanmonuments:{n}")})) - .chain([json!({"processor_type": "betterwitchhuts:fence_leg_processor"})]) - .collect(); - let mut list = json!({"processors": processors}); - let mut carried = BTreeMap::new(); - assert!(carry( - "processor_list", - &mut list, - &ProcessorData::default(), - &mut carried - )); - let p = list["processors"].as_array().unwrap(); - let types: Vec<&str> = p - .iter() - .map(|p| p["processor_type"].as_str().unwrap()) - .collect(); - let mut want = vec!["horizon:pick", "horizon:pick", "minecraft:rule"]; - want.extend(["horizon:pick"; 4]); - want.extend([ - "horizon:keep_world_block", - "horizon:flood_air", - "horizon:waterlog", - "minecraft:rule", - "horizon:pick", - "horizon:yung_pillar", - "horizon:yung_pillar", - ]); - assert_eq!(types, want); - assert_eq!(carried.values().sum::(), 11); - // Copper stairs keep their properties, each chance on a new float. - let stairs = &p[5]; - assert_eq!(stairs["block"], "minecraft:oxidized_cut_copper_stairs"); - assert_eq!( - stairs["picks"][1]["state"]["id"], - "minecraft:weathered_cut_copper_stairs" - ); - assert_eq!( - (stairs["redraw"].clone(), stairs["keep_properties"].clone()), - (json!(true), json!(true)) - ); - assert_eq!(p[0]["picks"][0]["state"]["properties"]["type"], "top"); - assert_eq!(p[1]["default"]["state"]["id"], "minecraft:water"); - assert_eq!( - p[12]["target_block_output"]["defaultBlockState"]["id"], - "minecraft:prismarine_bricks" - ); - assert_eq!(p[13]["keep_properties"], true); - } - #[test] fn repurposed_structure_voids_keep_the_world() { let mut list = json!({"processors": [ diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 91b659217..1070b2aad 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -13,6 +13,11 @@ //! by name. Each rewrite is counted in the carry report, and every type left //! as it is is listed, so the coverage report can say what generates and how //! closely. +//! +//! YUNG's, Lithostitched's and CTOV's worldgen files are converted by +//! `legacy_structure_mods`, called from [`upgrade`], [`crate::carry`] and the +//! processors. +use crate::legacy_structure_mods::{lithostitched, yung}; use serde_json::Value; use std::{ collections::{BTreeMap, BTreeSet}, @@ -21,8 +26,7 @@ use std::{ }; /// Structure types that are vanilla's jigsaw with extra start rules. -const JIGSAWS: [&str; 3] = [ - "lithostitched:jigsaw", +const JIGSAWS: [&str; 2] = [ "moogs_structures:moogs_structures_generic_jigsaw_structure", "repurposed_structures:generic_jigsaw_structure", ]; @@ -57,35 +61,6 @@ const SPREADS: [&str; 2] = [ "moogs_structures:advanced_random_spread", "repurposed_structures:advanced_random_spread", ]; -/// YUNG's placements: vanilla's random spread with an enhanced exclusion -/// zone (several sets), plus, for the temples, no start near an ocean or a -/// river, and for strongholds, starts only in odd rings around the origin. -const YUNG_SPREADS: [&str; 4] = [ - "yungsapi:enhanced_random_spread", - "betterdeserttemples:desert_temple", - "betterjungletemples:jungle_temple", - "betterstrongholds:stronghold", -]; -/// YUNG's structures and the vanilla structure type each one's mod turns -/// off (its DisableVanilla*Mixin, on by default in each mod's config). -const YUNG_REPLACES: [(&str, &str); 7] = [ - ( - "betterdeserttemples:desert_temple", - "minecraft:desert_pyramid", - ), - ( - "betterjungletemples:jungle_temple", - "minecraft:jungle_temple", - ), - ("betterwitchhuts:witch_hut", "minecraft:swamp_hut"), - ( - "betteroceanmonuments:ocean_monument", - "minecraft:ocean_monument", - ), - ("betterstrongholds:stronghold", "minecraft:stronghold"), - ("betterfortresses:fortress", "minecraft:fortress"), - ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), -]; /// Mo' Structures' placement (`mostructures:type`) takes its spacing and /// separation from the mod's config, not its files: the defaults it writes /// (MoStructuresConfig), by config key, as (spacing, separation). @@ -130,8 +105,8 @@ const LAYOUT_RULES: [&str; 4] = [ ]; /// The libraries' terrain kernel field, the game's /// `horizon:enhanced_terrain_adaptation` (docs/mods.md). -const ENHANCED_TERRAIN: &str = "enhanced_terrain_adaptation"; -const HORIZON_ENHANCED_TERRAIN: &str = "horizon:enhanced_terrain_adaptation"; +pub(crate) const ENHANCED_TERRAIN: &str = "enhanced_terrain_adaptation"; +pub(crate) const HORIZON_ENHANCED_TERRAIN: &str = "horizon:enhanced_terrain_adaptation"; /// Fields of older versions the mods' codecs no longer read: their own /// structures ignore them, and so does carry. Repurposed's jungle fortress /// and End stronghold still write `vertical_distance_from_start_piece`. @@ -181,195 +156,6 @@ pub struct Upgrade { /// `data//worldgen//horizon_added/.json`. pub const ADDED: &str = "horizon_added"; -/// A lithostitched worldgen modifier -/// (`data//lithostitched/worldgen_modifier/`) that adds to structure -/// sets or template pools, as a file the game merges into them (the key -/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The -/// modifier's conditions are checked against `loaded`, the mods ported -/// along: a compat addition for a mod that is not would place that mod's -/// blocks, which the game does not have. Other modifier types are left out. -/// Both are counted in `report`. -pub fn modifier( - v: &Value, - loaded: &dyn Fn(&str) -> bool, - report: &mut Upgrade, -) -> Option<(&'static str, Value)> { - let t = v["type"].as_str().unwrap_or_default(); - let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1; - let (kind, targets, from, to) = match t { - "lithostitched:add_structure_set_entries" => { - ("structure_set", "structure_sets", "entries", "structures") - } - "lithostitched:add_template_pool_elements" => { - ("template_pool", "template_pools", "elements", "elements") - } - _ => { - left(t); - return None; - } - }; - if !conditions_hold(v, loaded) { - left("conditions"); - return None; - } - let targets: Option> = match &v[targets] { - Value::String(s) => Some(vec![s.as_str()]), - Value::Array(a) => a.iter().map(Value::as_str).collect(), - _ => None, - }; - let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#'))) - else { - left("target"); - return None; - }; - let entries = v[from].as_array().cloned().unwrap_or_default(); - for target in &targets { - *report.added_to.entry((*target).to_owned()).or_default() += entries.len(); - } - Some(( - kind, - serde_json::json!({"horizon:add_to": targets, to: entries}), - )) -} - -/// Whether a modifier's load conditions hold: lithostitched's `predicate`, -/// and the loader's conditions (NeoForge's, else Fabric's). A condition -/// type not known here does not hold. -fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { - let all = |list: &Value, test: &dyn Fn(&Value) -> bool| { - list.as_array().is_some_and(|a| a.iter().all(test)) - }; - fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { - let test = |q: &Value| predicate(q, loaded); - let list = &p["predicates"]; - match p["type"] - .as_str() - .map(|t| t.trim_start_matches("lithostitched:")) - { - Some("true") => true, - Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded), - Some("not") => !predicate(&p["predicate"], loaded), - Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)), - Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)), - _ => false, - } - } - fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { - let test = |q: &Value| neoforge(q, loaded); - match c["type"].as_str() { - Some("neoforge:true") => true, - Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded), - Some("neoforge:not") => !neoforge(&c["value"], loaded), - Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), - Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), - _ => false, - } - } - fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { - let test = |q: &Value| fabric(q, loaded); - let mods = || { - c["values"] - .as_array() - .into_iter() - .flatten() - .map(Value::as_str) - }; - match c["condition"].as_str() { - Some("fabric:true") => true, - Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)), - Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)), - Some("fabric:not") => !fabric(&c["value"], loaded), - Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), - Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), - _ => false, - } - } - let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded)); - let loader = match ( - v.get("neoforge:conditions"), - v.get("fabric:load_conditions"), - ) { - (Some(c), _) => all(c, &|c| neoforge(c, loaded)), - // One condition or a list of them. - (None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)), - (None, Some(c)) => fabric(c, loaded), - (None, None) => true, - }; - litho && loader -} - -/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds -/// to vanilla's `villages` and `pillager_outposts` sets in Java code -/// (`CTOV.registerstructure`, through lithostitched), with its default -/// config: every village type in three sizes, weighted 10, 4 and 1, and -/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each). -const CTOV_VILLAGES: [&str; 21] = [ - "beach", - "christmas", - "desert", - "desert_oasis", - "dark_forest", - "jungle", - "jungle_tree", - "mesa", - "mesa_fortified", - "mountain", - "mountain_alpine", - "mushroom", - "plains", - "plains_fortified", - "savanna", - "savanna_na", - "snowy_igloo", - "swamp", - "swamp_fortified", - "taiga", - "taiga_fortified", -]; -const CTOV_OUTPOSTS: [&str; 11] = [ - "beach", - "dark_forest", - "desert", - "jungle", - "badlands", - "mountain", - "plains", - "savanna", - "snowy", - "swamp", - "taiga", -]; - -/// The entries a mod adds to other structure sets in Java code, as its -/// default config has them: (file name, set, `[(structure, weight)]`). -/// Lithostitched appends them in the order of a hash map of every modifier -/// in the pack, which carry cannot know; they are written in the order the -/// mod registers them. Each set picks by weight, so how often each starts -/// is the same. -pub fn code_set_entries(mod_id: &str) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> { - match mod_id { - "ctov" => { - let outposts = CTOV_OUTPOSTS - .iter() - .map(|v| (format!("ctov:pillager_outpost_{v}"), 1)) - .collect(); - let villages = [("small", 10), ("medium", 4), ("large", 1)] - .into_iter() - .flat_map(|(size, weight)| { - CTOV_VILLAGES - .iter() - .map(move |v| (format!("ctov:{size}/village_{v}"), weight)) - }) - .collect(); - vec![ - ("pillager_outposts", "minecraft:pillager_outposts", outposts), - ("villages", "minecraft:villages", villages), - ] - } - _ => Vec::new(), - } -} - /// Rewrites one `data//worldgen//...` file in place; whether it /// changed. /// `set_tags` are the mod's structure set tags, expanded @@ -474,15 +260,16 @@ fn upgrade_types( set_tags: &BTreeMap>, ) -> bool { let lost = &mut report.rules_lost; + // YUNG's and Lithostitched's types are converted apart from this code. + if let Some(changed) = + yung::upgrade(kind, v, set_tags, lost).or_else(|| lithostitched::upgrade(kind, v, lost)) + { + report.mapped += usize::from(changed); + return changed; + } let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1; let changed = match kind { "structure" => match v["type"].as_str() { - // Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a - // config switch that ships on. - Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => { - yung_structure(v, lost); - true - } Some(t) if JIGSAWS.contains(&t) || NETHER_JIGSAWS.contains(&t) @@ -591,11 +378,6 @@ fn upgrade_types( true } Some("mostructures:type") => mo_placement(&mut v["placement"], lost), - Some(t) if YUNG_SPREADS.contains(&t) => { - let t = t.to_owned(); - yung_placement(&t, &mut v["placement"], set_tags, lost); - true - } Some(t) if !t.starts_with("minecraft:") => { unsupported(t); false @@ -615,6 +397,10 @@ fn upgrade_types( } } for element in elements { + if yung::upgrade_pool_element(element, lost) { + changed = true; + continue; + } let Some(t) = element["element_type"].as_str() else { continue; }; @@ -629,9 +415,6 @@ fn upgrade_types( } element["element_type"] = (*to).into(); changed = true; - } else if t == "yungsapi:yung_single_element" { - yung_element(element, lost); - changed = true; } else if t == "formations:single_pool_element" { // Vanilla's element with its own ground level (1 when // missing, as its codec reads it). @@ -653,167 +436,10 @@ fn upgrade_types( changed } -/// YUNG's API's jigsaw as vanilla's, laid out by its own assembler in the -/// game (`horizon:yungsapi`, `horizon_world::worldgen::structure::yung`): -/// the heights pieces stay within move under the key, its terrain -/// adaptation under `horizon:enhanced_terrain_adaptation`. A start offset in -/// the chunk is lost. -fn yung_structure(v: &mut Value, lost: &mut BTreeMap) { - let Some(o) = v.as_object_mut() else { - return; - }; - o.insert("type".into(), "minecraft:jigsaw".into()); - let mut rules = serde_json::Map::new(); - for key in ["min_y", "max_y"] { - if let Some(y) = o.remove(key) { - rules.insert(key.into(), y); - } - } - // YungJigsawStructure's adaptation (NONE by default): every piece's - // junctions, and the start's box grown by its radius. - let own = o.remove(ENHANCED_TERRAIN); - let mut kernel = yung_terrain(own.as_ref().unwrap_or(&Value::Null), lost); - kernel["rigid_junctions"] = true.into(); - kernel["inflate"] = true.into(); - o.insert(HORIZON_ENHANCED_TERRAIN.into(), kernel); - for key in ["x_offset_in_chunk", "z_offset_in_chunk"] { - if o.remove(key).is_some_and(|n| n != 0) { - *lost.entry(key.into()).or_default() += 1; - } - } - o.insert("horizon:yungsapi".into(), rules.into()); -} - -/// YUNG's single pool element as vanilla's, its rules under -/// `horizon:yungsapi`: name and `max_count`, depth range, priority, -/// `ignore_bounds`, its condition, dead-end pool and modifiers; its terrain -/// adaptation under `horizon:enhanced_terrain_adaptation`. -fn yung_element(element: &mut Value, lost: &mut BTreeMap) { - let Some(o) = element.as_object_mut() else { - return; - }; - o.insert( - "element_type".into(), - "minecraft:single_pool_element".into(), - ); - let mut rules = serde_json::Map::new(); - for (from, to) in [ - ("name", "name"), - ("max_count", "max_count"), - ("min_required_depth", "min_depth"), - ("max_possible_depth", "max_depth"), - ("is_priority", "priority"), - ("ignore_bounds", "ignore_bounds"), - ] { - if let Some(x) = o.remove(from) { - rules.insert(to.into(), x); - } - } - if let Some(c) = o.remove("condition") { - rules.insert("condition".into(), yung_condition(&c, lost)); - } - // A piece's own adaptation, NONE included, replaces its structure's. - if let Some(a) = o.remove(ENHANCED_TERRAIN) { - o.insert(HORIZON_ENHANCED_TERRAIN.into(), yung_terrain(&a, lost)); - } - if let Some(pool) = o.remove("deadend_pool").filter(Value::is_string) { - rules.insert("deadend_pool".into(), pool); - } - let modifiers: Vec = o - .remove("modifiers") - .and_then(|m| m.as_array().cloned()) - .unwrap_or_default() - .iter() - .filter_map(|m| yung_modifier(m, lost)) - .collect(); - if !modifiers.is_empty() { - rules.insert("modifiers".into(), modifiers.into()); - } - o.insert("horizon:yungsapi".into(), rules.into()); -} - -/// One of YUNG's structure modifiers in the game's terms: its condition and -/// its transform and delay_generation actions, on the piece itself (`self`, -/// the API's only target). Another target loses the modifier, another action -/// just that action. -fn yung_modifier(m: &Value, lost: &mut BTreeMap) -> Option { - let target = m["target_selector"]["type"].as_str().unwrap_or_default(); - if target != "yungsapi:self" { - *lost - .entry(format!("yungsapi modifier target {target}")) - .or_default() += 1; - return None; - } - let mut actions = Vec::new(); - for a in m["actions"].as_array().into_iter().flatten() { - let int = |k: &str| a[k].as_i64().unwrap_or(0); - match a["type"].as_str().unwrap_or_default() { - "yungsapi:transform" => actions.push(serde_json::json!({"type": "transform", - "output": a["output"].clone(), - "offset": [int("x_offset"), int("y_offset"), int("z_offset")]})), - "yungsapi:delay_generation" => { - actions.push(serde_json::json!({"type": "delay_generation"})) - } - other => { - *lost - .entry(format!("yungsapi modifier action {other}")) - .or_default() += 1 - } - } - } - let condition = match m.get("condition") { - Some(c) => yung_condition(c, lost), - None => serde_json::json!({"type": "true"}), - }; - Some(serde_json::json!({"condition": condition, "actions": actions})) -} - -/// YUNG's API's terrain adaptation as the game's kernel: its two presets -/// spelled out, NONE (also the default) as size 0. An aquifer override -/// (none of ATM10's) is lost. -fn yung_terrain(a: &Value, lost: &mut BTreeMap) -> Value { - let kernel = |size: i32, distance: i32, top: &str, bottom: &str| { - serde_json::json!({"kernel_size": size, "kernel_distance": distance, - "top": top, "bottom": bottom}) - }; - match a["type"].as_str() { - Some("yungsapi:carved_top_no_beard_large") => kernel(24, 16, "carve", "none"), - Some("yungsapi:carved_top_no_beard_small") => kernel(12, 6, "carve", "none"), - Some("yungsapi:custom") => { - let mut out = serde_json::Map::new(); - for key in [ - "kernel_size", - "kernel_distance", - "top", - "bottom", - "bottom_offset", - "padding", - ] { - if let Some(x) = a.get(key) { - out.insert(key.into(), x.clone()); - } - } - if a.get("aquifer_override") - .is_some_and(|x| x["type"] != "yungsapi:none") - { - *lost.entry("yungsapi aquifer_override".into()).or_default() += 1; - } - moogs_terrain(&out.into(), lost).unwrap_or_else(|| kernel(0, 0, "none", "none")) - } - None | Some("yungsapi:none") => kernel(0, 0, "none", "none"), - Some(other) => { - *lost - .entry(format!("yungsapi terrain adaptation {other}")) - .or_default() += 1; - kernel(0, 0, "none", "none") - } - } -} - /// MoogsStructureLib's terrain adaptation: already the game's shape (with /// its band), when it has the fields the game needs (else it is lost, as /// the library's codec would refuse it). -fn moogs_terrain(a: &Value, lost: &mut BTreeMap) -> Option { +pub(crate) fn moogs_terrain(a: &Value, lost: &mut BTreeMap) -> Option { let ok = ["kernel_size", "kernel_distance"] .iter() .all(|k| a[k].is_u64()) @@ -824,58 +450,15 @@ fn moogs_terrain(a: &Value, lost: &mut BTreeMap) -> Option ok.then(|| a.clone()) } -/// One of YUNG's structure conditions in the game's terms. `mod_loaded` -/// holds for Minecraft alone: a mod that needs code is not ported, and the -/// pieces it guards would place its blocks. A condition the game does not -/// have does not hold, and is counted. -fn yung_condition(c: &Value, lost: &mut BTreeMap) -> Value { - let t = c["type"].as_str().unwrap_or_default(); - let list = |lost: &mut BTreeMap| -> Value { - let all = c["conditions"].as_array().into_iter().flatten(); - all.map(|x| yung_condition(x, lost)) - .collect::>() - .into() - }; - let opt = |k: &str| c.get(k).cloned().unwrap_or(Value::Null); - match t.trim_start_matches("yungsapi:") { - "always_true" => serde_json::json!({"type": "true"}), - "not" => { - serde_json::json!({"type": "not", "condition": yung_condition(&c["condition"], lost)}) - } - "all_of" => serde_json::json!({"type": "all_of", "conditions": list(lost)}), - "any_of" => serde_json::json!({"type": "any_of", "conditions": list(lost)}), - "depth" => serde_json::json!({"type": "depth", - "min_depth": opt("min_required_depth"), "max_depth": opt("max_possible_depth")}), - "altitude" => serde_json::json!({"type": "altitude", - "bottom": opt("bottom_cutoff_y"), "top": opt("top_cutoff_y")}), - "random_chance" => serde_json::json!({"type": "random_chance", "chance": opt("chance")}), - "rotation" => serde_json::json!({"type": "rotation", "rotations": opt("rotations")}), - "piece_in_horizontal_direction" => { - // "yungsapi:all" (or no list) matches any piece. - let pieces: Vec = c["pieces"].as_array().cloned().unwrap_or_default(); - let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all"); - serde_json::json!({"type": "piece_in_horizontal_direction", - "pieces": if any { Vec::new() } else { pieces }, - "range": opt("range"), "rotation": opt("rotation")}) - } - // The game reads "yungsapi:all" (or no list) as any piece. - "piece_in_range" => serde_json::json!({"type": "piece_in_range", - "pieces": c.get("pieces").cloned().unwrap_or_else(|| Vec::::new().into()), - "horizontal_range": opt("horizontal_range"), "above_range": opt("above_range"), - "below_range": opt("below_range")}), - "mod_loaded" if c["modid"] == "minecraft" => serde_json::json!({"type": "true"}), - "mod_loaded" => serde_json::json!({"type": "false"}), - _ => { - *lost.entry(format!("yungsapi condition {t}")).or_default() += 1; - serde_json::json!({"type": "false"}) - } - } -} - /// Moves a Repurposed Structures or Moog's jigsaw's start rules under /// `horizon:start_checks`, and counts the layout rules it loses. `liquid` is /// the block its no-start-in-liquid rule reads. -fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap, limited: bool) { +pub(crate) fn start_checks( + v: &mut Value, + liquid: &str, + lost: &mut BTreeMap, + limited: bool, +) { let Some(o) = v.as_object_mut() else { return; }; @@ -1043,7 +626,7 @@ fn moogs_spacing(p: &mut Value, lost: &mut BTreeMap) { /// An advanced random spread's minimum distance from the world origin and /// its super exclusion zone (sets named by a tag) under `horizon:` keys. -fn placement_rules( +pub(crate) fn placement_rules( p: &mut Value, set_tags: &BTreeMap>, lost: &mut BTreeMap, @@ -1115,65 +698,6 @@ fn mo_placement(p: &mut Value, lost: &mut BTreeMap) -> bool { true } -/// One of YUNG's placements as vanilla's random spread with `horizon:` keys: -/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' -/// ocean and river search (findBiomeHorizontal around the chunk's middle -/// block at y 120, 48 blocks, every 2 quarts) as `horizon:avoid_biomes`; the -/// strongholds' rings as `horizon:ring_sections`. -fn yung_placement( - t: &str, - p: &mut Value, - set_tags: &BTreeMap>, - lost: &mut BTreeMap, -) { - placement_rules(p, set_tags, lost); - p["type"] = "minecraft:random_spread".into(); - let Some(o) = p.as_object_mut() else { - return; - }; - match t { - "betterdeserttemples:desert_temple" | "betterjungletemples:jungle_temple" => { - o.insert( - "horizon:avoid_biomes".into(), - serde_json::json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], - "radius": 48, "step": 2, "y": 120}), - ); - } - "betterstrongholds:stronghold" => { - let mut rings = serde_json::Map::new(); - for (from, to) in [ - ("chunk_distance_to_first_ring", "distance_to_first_ring"), - ("ring_chunk_thickness", "thickness"), - ("max_ring_section", "max_section"), - ] { - if let Some(n) = o.remove(from) { - rings.insert(to.into(), n); - } - } - o.insert("horizon:ring_sections".into(), rings.into()); - } - _ => {} - } -} - -/// Marks a YUNG's structure that the game can start (its type is vanilla's -/// after the upgrade) with the vanilla type its mod turns off, under -/// `horizon:disables`. One the game cannot start leaves the vanilla -/// structure in place, so the world keeps one of the two. -pub fn disables(id: &str, v: &mut Value) -> bool { - let Some((_, vanilla)) = YUNG_REPLACES.iter().find(|(s, _)| id.starts_with(s)) else { - return false; - }; - if !v["type"] - .as_str() - .is_some_and(|t| t.starts_with("minecraft:")) - { - return false; - } - v["horizon:disables"] = serde_json::json!([vanilla]); - true -} - /// The mod's structure set tags (`data//tags/worldgen/structure_set/`), /// by tag id, with the tags they include expanded. Optional entries /// (`{"id": ..., "required": false}`) count as their id. @@ -1590,94 +1114,6 @@ mod tests { assert_eq!(report.rules_lost["super_exclusion_zone"], 1); } - #[test] - fn yungs_jigsaws_keep_their_rules() { - let mut report = Upgrade::default(); - let mut s = json!({"type": "yungsapi:yung_jigsaw", "start_pool": "y:start", "size": 20, - "max_y": 60, "x_offset_in_chunk": 0, "max_distance_from_center": 80, - "enhanced_terrain_adaptation": {"type": "yungsapi:custom", "kernel_size": 24, - "kernel_distance": 24, "top": "carve", "bottom": "none"}}); - assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); - assert_eq!(s["type"], "minecraft:jigsaw"); - assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); - assert_eq!( - s["horizon:enhanced_terrain_adaptation"], - json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", "bottom": "none", - "rigid_junctions": true, "inflate": true}) - ); - for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { - assert!(s.get(gone).is_none(), "{gone}"); - } - // Better Dungeons' small Nether dungeon is the same jigsaw. - let mut nether = json!({"type": "betterdungeons:small_nether_dungeon", - "start_pool": "betterdungeons:small_nether_dungeon", "size": 10, - "start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor", - "max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"}); - assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); - assert_eq!(nether["type"], "minecraft:jigsaw"); - assert_eq!(nether["horizon:yungsapi"], json!({})); - assert_eq!( - nether["horizon:enhanced_terrain_adaptation"], - json!({"kernel_size": 0, "kernel_distance": 0, "top": "none", "bottom": "none", - "rigid_junctions": true, "inflate": true}) - ); - assert_eq!( - nether["start_jigsaw_name"], - "betterdungeons:small_nether_dungeon_anchor" - ); - assert!(report.unsupported.is_empty()); - let mut pool = json!({"elements": [{"weight": 3, "element": { - "element_type": "yungsapi:yung_single_element", "location": "y:room", - "processors": "minecraft:empty", "projection": "rigid", - "name": "room", "max_count": 2, "min_required_depth": 1, "is_priority": true, - "ignore_bounds": false, "deadend_pool": "y:end", - "modifiers": [ - {"condition": {"type": "yungsapi:piece_in_range", "pieces": ["y:pillar"], - "above_range": 40}, - "target_selector": {"type": "yungsapi:self"}, - "actions": [{"type": "yungsapi:transform", "output": ["y:covered"], "x_offset": -1}, - {"type": "yungsapi:delay_generation"}, {"type": "yungsapi:spin"}]}, - {"condition": {"type": "yungsapi:always_true"}, - "target_selector": {"type": "yungsapi:all"}, "actions": []}], - "enhanced_terrain_adaptation": {"type": "yungsapi:carved_top_no_beard_small"}, - "condition": {"type": "yungsapi:all_of", "conditions": [ - {"type": "yungsapi:piece_in_horizontal_direction", "pieces": ["yungsapi:all"], - "range": 5, "rotation": "none"}, - {"type": "yungsapi:not", "condition": {"type": "yungsapi:mod_loaded", "modid": "create"}}, - {"type": "yungsapi:biome", "biomes": []}]}}}]}); - assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); - let e = &pool["elements"][0]["element"]; - assert_eq!(e["element_type"], "minecraft:single_pool_element"); - assert_eq!(e["location"], "y:room"); - assert_eq!( - e["horizon:yungsapi"], - json!({"name": "room", "max_count": 2, "min_depth": 1, "priority": true, - "ignore_bounds": false, "condition": {"type": "all_of", "conditions": [ - {"type": "piece_in_horizontal_direction", "pieces": [], "range": 5, "rotation": "none"}, - {"type": "not", "condition": {"type": "false"}}, - {"type": "false"}]}, - "deadend_pool": "y:end", - "modifiers": [{"condition": {"type": "piece_in_range", "pieces": ["y:pillar"], - "horizontal_range": null, "above_range": 40, "below_range": null}, - "actions": [{"type": "transform", "output": ["y:covered"], "offset": [-1, 0, 0]}, - {"type": "delay_generation"}]}]}) - ); - assert!(e.get("deadend_pool").is_none() && e.get("modifiers").is_none()); - assert_eq!( - e["horizon:enhanced_terrain_adaptation"], - json!({"kernel_size": 12, "kernel_distance": 6, "top": "carve", "bottom": "none"}) - ); - assert_eq!( - report.rules_lost, - BTreeMap::from([ - ("yungsapi condition yungsapi:biome".into(), 1), - ("yungsapi modifier action yungsapi:spin".into(), 1), - ("yungsapi modifier target yungsapi:all".into(), 1), - ]) - ); - assert!(report.unsupported.is_empty()); - } - #[test] fn drops_processors_written_in_java() { let mut report = Upgrade::default(); @@ -1722,59 +1158,6 @@ mod tests { ); } - #[test] - fn yungs_placements_keep_their_rules() { - let tags = BTreeMap::from([( - "bf:avoid".to_owned(), - vec!["minecraft:nether_complexes".to_owned()], - )]); - let mut report = Upgrade::default(); - let mut fortress = json!({"placement": {"type": "yungsapi:enhanced_random_spread", - "salt": 1, "spacing": 30, "separation": 20, - "enhanced_exclusion_zone": {"other_set": "#bf:avoid", "chunk_count": 10}}}); - assert!(upgrade("structure_set", &mut fortress, &mut report, &tags)); - assert_eq!( - fortress["placement"], - json!({"type": "minecraft:random_spread", "salt": 1, "spacing": 30, "separation": 20, - "horizon:exclusion_zone": {"other_sets": ["minecraft:nether_complexes"], "chunk_count": 10}}) - ); - let mut temple = json!({"placement": {"type": "betterdeserttemples:desert_temple", - "salt": 2, "spacing": 30, "separation": 20, - "exclusion_zone": {"other_set": "minecraft:villages", "chunk_count": 6}}}); - assert!(upgrade("structure_set", &mut temple, &mut report, &tags)); - assert_eq!(temple["placement"]["type"], "minecraft:random_spread"); - assert_eq!(temple["placement"]["exclusion_zone"]["chunk_count"], 6); - assert_eq!( - temple["placement"]["horizon:avoid_biomes"], - json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], - "radius": 48, "step": 2, "y": 120}) - ); - let mut stronghold = json!({"placement": {"type": "betterstrongholds:stronghold", - "salt": 3, "spacing": 85, "separation": 50, - "chunk_distance_to_first_ring": 80, "ring_chunk_thickness": 96}}); - assert!(upgrade( - "structure_set", - &mut stronghold, - &mut report, - &tags - )); - assert_eq!( - stronghold["placement"], - json!({"type": "minecraft:random_spread", "salt": 3, "spacing": 85, "separation": 50, - "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96}}) - ); - assert_eq!(report.mapped, 3); - assert!(report.unsupported.is_empty()); - // The vanilla counterpart is turned off only for a structure the game starts. - let mut ported = json!({"type": "minecraft:jigsaw"}); - assert!(disables("betterstrongholds:stronghold", &mut ported)); - assert_eq!(ported["horizon:disables"], json!(["minecraft:stronghold"])); - let mut java = json!({"type": "bettermineshafts:mineshaft"}); - assert!(!disables("bettermineshafts:mineshaft_oak", &mut java)); - let mut circle = json!({"type": "minecraft:jigsaw"}); - assert!(!disables("betterwitchhuts:witch_circle", &mut circle)); - } - #[test] fn piece_limited_jigsaws_keep_their_layout() { let mut report = Upgrade::default(); @@ -1886,88 +1269,6 @@ mod tests { assert_eq!(report.mapped, 0); } - #[test] - fn modifiers_add_to_sets_and_pools() { - let mut report = Upgrade::default(); - let only_fd = |m: &str| m == "farmersdelight"; - let set = json!({"type": "lithostitched:add_structure_set_entries", - "structure_sets": "minecraft:villages", - "entries": [{"structure": "x:village", "weight": 4}]}); - let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap(); - assert_eq!(kind, "structure_set"); - assert_eq!( - added, - json!({"horizon:add_to": ["minecraft:villages"], - "structures": [{"structure": "x:village", "weight": 4}]}) - ); - // A compat addition holds only when its mod is ported along. - let pool = |modid: &str| { - json!({"type": "lithostitched:add_template_pool_elements", - "neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}], - "fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]}, - "template_pools": ["x:houses", "y:houses"], - "elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element", - "location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]}) - }; - let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap(); - assert_eq!(kind, "template_pool"); - assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"])); - assert_eq!(added["elements"][0]["weight"], 5); - assert!(modifier(&pool("create"), &only_fd, &mut report).is_none()); - // Fabric's conditions when there are no NeoForge ones; lithostitched's own. - let fabric = json!({"type": "lithostitched:add_structure_set_entries", - "fabric:load_conditions": [{"condition": "fabric:not", - "value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}], - "predicate": {"type": "lithostitched:all_of", "predicates": [ - {"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"}, - {"type": "lithostitched:true"}]}, - "structure_sets": "minecraft:villages", "entries": []}); - assert!(modifier(&fabric, &only_fd, &mut report).is_some()); - let tagged = json!({"type": "lithostitched:add_structure_set_entries", - "structure_sets": "#x:sets", "entries": []}); - assert!(modifier(&tagged, &only_fd, &mut report).is_none()); - let features = json!({"type": "lithostitched:add_features"}); - assert!(modifier(&features, &only_fd, &mut report).is_none()); - assert_eq!( - report.added_to, - BTreeMap::from([ - ("minecraft:villages".into(), 1), - ("x:houses".into(), 1), - ("y:houses".into(), 1), - ]) - ); - assert_eq!( - report.modifiers_left, - BTreeMap::from([ - ("conditions".into(), 1), - ("lithostitched:add_features".into(), 1), - ("target".into(), 1), - ]) - ); - } - - #[test] - fn ctov_joins_vanillas_villages_and_outposts() { - let sets = code_set_entries("ctov"); - let (file, set, outposts) = &sets[0]; - assert_eq!( - (*file, *set), - ("pillager_outposts", "minecraft:pillager_outposts") - ); - assert_eq!(outposts.len(), 11); - assert!(outposts.iter().all(|(_, w)| *w == 1)); - let (_, set, villages) = &sets[1]; - assert_eq!(*set, "minecraft:villages"); - assert_eq!(villages.len(), 63); - assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10)); - assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4)); - assert_eq!( - villages[62], - ("ctov:large/village_taiga_fortified".into(), 1) - ); - assert!(code_set_entries("mvs").is_empty()); - } - #[test] fn convention_tags_include_theirs() { let conventions = BTreeMap::from([