) -> Option {
+ let t = self.theme;
+ let o = self.mods.browse.open.as_ref()?;
+ let p = o.project.clone();
+ let tab = o.tab;
+ let support = self.mods.support(&p);
+ let color = match support {
+ Support::Works => t.success,
+ Support::Partial(_) => t.accent,
+ Support::No(_) => t.muted,
+ };
+ let back = button("mods-back", "Back to results", Kind::Ghost, &t).on_click(cx.listener(
+ |this, _: &ClickEvent, _, cx| {
+ this.mods.browse.open = None;
+ cx.notify();
+ },
+ ));
+ let details = o.details.clone();
+ let versions = o.versions.clone();
+ let mut meta = vec![format!("{} downloads", thousands(p.downloads))];
+ if let Some(Ok(d)) = &details {
+ meta.push(format!("{} followers", thousands(d.followers)));
+ if let Some(day) = d.updated.get(..10) {
+ meta.push(format!("updated {day}"));
+ }
+ }
+ if !p.license.is_empty() {
+ meta.push(p.license.clone());
+ }
+ meta.push(format!("from {}", p.source.label()));
+ let authors = match &details {
+ Some(Ok(d)) if !d.authors.is_empty() => d.authors.join(", "),
+ _ => p.author.clone(),
+ };
+ let icon = self.mods_icon(&p, 72.);
+ let busy = self.mods.busy.as_ref().map(|b| b.0.clone());
+ let installed = self.mods.entry(&p).is_some();
+ let checking = matches!(
+ self.mods.checks.get(&(p.source, p.id.clone())),
+ None | Some(Checking::Running)
+ ) && p.kind == PackKind::Mod
+ && p.support().installable();
+ let mut action = div().flex().items_center().gap(px(8.)).child(
+ caps(if checking {
+ "Checking"
+ } else {
+ support.label()
+ })
+ .flex_none()
+ .text_color(color),
+ );
+ if busy.as_deref() == Some(p.id.as_str()) {
+ action = action.child(caps("Installing").text_color(t.accent));
+ } else if installed {
+ action = action.child(caps("Installed").text_color(t.muted));
+ } else if support.installable() && !checking {
+ let label = if p.kind == PackKind::Modpack {
+ "Import"
+ } else {
+ "Install"
+ };
+ let mut install = button("mods-page-install", label, Kind::Primary, &t);
+ if busy.is_some() {
+ install = disabled(install);
+ } else {
+ let p = p.clone();
+ install = install.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
+ this.mods_install(p.source, p.id.clone(), Some(p.clone()));
+ cx.notify();
+ }));
+ }
+ action = action.child(install);
+ }
+ let head = div()
+ .flex()
+ .items_center()
+ .gap(px(20.))
+ .child(icon)
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w_0()
+ .gap(px(4.))
+ .child(text(theme::TITLE).text_color(t.ink).child(p.title.clone()))
+ .child(
+ text(theme::UI)
+ .text_color(t.muted)
+ .child(if authors.is_empty() {
+ p.summary.clone()
+ } else {
+ format!("by {authors} · {}", p.summary)
+ }),
+ )
+ .child(
+ text(theme::CAPTION)
+ .text_color(t.muted)
+ .child(meta.join(" · ")),
+ ),
+ )
+ .child(action);
+ let mut page = div()
+ .flex()
+ .flex_col()
+ .gap(px(24.))
+ .child(div().flex().child(back))
+ .child(head);
+ if let Some(why) = support.reason() {
+ page = page.child(
+ text(theme::UI)
+ .text_color(t.ink_soft)
+ .child(why.to_string()),
+ );
+ }
+ if let Some(Checking::Done(c)) = self.mods.checks.get(&(p.source, p.id.clone())) {
+ let lines = |title: &str, list: &[String]| {
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .child(caps(title).text_color(t.muted))
+ .children(
+ list.iter()
+ .map(|l| text(theme::CAPTION).text_color(t.ink_soft).child(l.clone())),
+ )
+ };
+ let mut what = div().flex().gap(px(32.));
+ if !c.ports.is_empty() {
+ what = what.child(lines("Ports", &c.ports));
+ }
+ if !c.skipped.is_empty() {
+ what = what.child(lines("Doesn't port", &c.skipped));
+ }
+ page = page.child(what);
+ }
+ if let Some(Ok(d)) = &details {
+ let mut links = div().flex().flex_wrap().gap(px(8.));
+ let page_url = p.page.clone();
+ if !page_url.is_empty() {
+ links = links.child(
+ button(
+ "mods-link-page",
+ format!("{} page", p.source.label()),
+ Kind::Ghost,
+ &t,
+ )
+ .on_click(move |_, _, cx| cx.open_url(&page_url)),
+ );
+ }
+ for (i, l) in d.links.iter().enumerate() {
+ let url = l.url.clone();
+ links = links.child(
+ button(format!("mods-link-{i}"), l.label.clone(), Kind::Ghost, &t)
+ .on_click(move |_, _, cx| cx.open_url(&url)),
+ );
+ }
+ page = page.child(links);
+ }
+ let this = cx.entity().downgrade();
+ page = page.child(div().flex().child(segments("mods-tab", &TABS, tab, &t, {
+ move |value, _, cx| {
+ let _ = this.update(cx, |this, cx| {
+ if let Some(o) = &mut this.mods.browse.open {
+ o.tab = value;
+ }
+ cx.notify();
+ });
+ }
+ })));
+ let body = match tab {
+ Tab::Description => match &details {
+ None => centered("Loading…", &t),
+ Some(Err(e)) => notice(e.clone(), &t),
+ Some(Ok(d)) => div().max_w(px(760.)).child(markdown::render(&d.body, &t)),
+ },
+ Tab::Gallery => match &details {
+ None => centered("Loading…", &t),
+ Some(Err(e)) => notice(e.clone(), &t),
+ Some(Ok(d)) if d.gallery.is_empty() => centered("No gallery images.", &t),
+ Some(Ok(d)) => {
+ let mut grid = div().flex().flex_wrap().gap(px(16.));
+ for g in &d.gallery {
+ let shot = match self.mods_image(&g.url, images::GALLERY) {
+ Some(path) => img(path).w(px(360.)).h(px(203.)).into_any_element(),
+ None => plate(&t).w(px(360.)).h(px(203.)).into_any_element(),
+ };
+ grid = grid.child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(6.))
+ .w(px(360.))
+ .child(plate(&t).overflow_hidden().child(shot))
+ .when(!g.title.is_empty(), |d| {
+ d.child(
+ text(theme::CAPTION)
+ .text_color(t.ink_soft)
+ .child(g.title.clone()),
+ )
+ }),
+ );
+ }
+ grid
+ }
+ },
+ Tab::Versions => match &versions {
+ None => centered("Loading…", &t),
+ Some(Err(e)) => notice(e.clone(), &t),
+ Some(Ok(list)) => {
+ let mut rows = div().flex().flex_col().border_t_1().border_color(t.rule);
+ for (i, v) in list.iter().take(50).enumerate() {
+ let file = v.file();
+ let mut detail = vec![
+ v.published.get(..10).unwrap_or_default().to_string(),
+ v.loaders.join(", "),
+ ];
+ let games: Vec<&str> = v
+ .game_versions
+ .iter()
+ .rev()
+ .take(4)
+ .map(String::as_str)
+ .collect();
+ detail.push(games.join(", "));
+ if let Some(f) = file {
+ detail.push(format!("{} · {:.1} MB", f.name, f.size as f64 / 1e6));
+ }
+ let checked = file.and_then(|f| {
+ (p.kind == PackKind::Mod)
+ .then(|| java::cached(&backend::game_home(), f))
+ .flatten()
+ });
+ rows = rows.child(index_row(
+ i + 1,
+ v.number.clone(),
+ Some(detail.join(" · ").into_any_element()),
+ checked.map(|c| {
+ caps(c.verdict.label())
+ .text_color(t.muted)
+ .into_any_element()
+ }),
+ &t,
+ ));
+ }
+ rows
+ }
+ },
+ };
+ Some(page.child(body))
+ }
+}
diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py
index 1f845ad86..85778d91d 100755
--- a/tools/lan_e2e.py
+++ b/tools/lan_e2e.py
@@ -129,6 +129,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
it (#1222).
- frames: the host and the guest each put a diamond in an item frame and turn it, and put a
helmet on an armor stand and take it back (#1222).
+- mounts: the host and the guest each open a tamed horse's, donkey's and llama's inventory
+ (shift + right click, then the inventory key while riding), put on a saddle, armour
+ or a carpet and fill the chest by shift-clicking.
- riding: the host and the guest each saddle and ride a horse (walk, jump), a pig and a strider
(with their sticks), a camel and a donkey, sit on a llama and fly a happy ghast, and
get off by sneaking; the other side sees the animal move.
@@ -175,7 +178,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
-CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'levels']
+CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels']
class Game:
@@ -2888,6 +2891,101 @@ def check_riding(host, guest, out):
return result
+# Mount inventories: (kind, summon NBT, what goes in by shift-click and the menu slot it lands
+# in: 700 the saddle, 701 the body armour or carpet, 710 the chest's first slot).
+MOUNT_MENUS = [
+ ('horse', '{Tame:1b,NoAI:1b}', [('minecraft:saddle', 700), ('minecraft:iron_horse_armor', 701)]),
+ ('donkey', '{Tame:1b,NoAI:1b,ChestedHorse:1b}', [('minecraft:saddle', 700), ('minecraft:dirt', 710)]),
+ ('llama', '{Tame:1b,NoAI:1b,ChestedHorse:1b,Strength:3}',
+ [('minecraft:red_carpet', 701), ('minecraft:dirt', 710)]),
+]
+
+
+def mount_screen(game, ticks=20):
+ """The open mount menu's slots and items ({700: 'minecraft:saddle', ...}), waiting up to
+ `ticks` for it to open; None when no mount menu opened."""
+ for _ in range(ticks // 2):
+ slots = {}
+ for w in game.raw('ui').get('widgets', []):
+ wid = w.get('id', '')
+ if wid.startswith('slot-') and wid[5:].isdigit() and int(wid[5:]) >= 700:
+ slots[int(wid[5:])] = (w.get('stack') or {}).get('item')
+ if slots:
+ return slots
+ game.wait(2)
+ return None
+
+
+def check_mounts(host, guest, out):
+ """The host and the guest each open a tamed horse's, donkey's and llama's inventory with
+ shift + right click (`ClientboundMountScreenOpenPacket` for a server's player), put on a
+ saddle, horse armour or a carpet and fill the chest by shift-clicking, close it, then ride the
+ mount and open its inventory with the inventory key (OPEN_INVENTORY): it shows what was put
+ in, and the server took the items from the inventory."""
+ spots = apart(host, guest)
+ result = {}
+ for label, player in (('host', host), ('guest', guest)):
+ x, y, z = spots[label]
+ player('command', command='gamemode survival')
+ result[label] = {}
+ for kind, nbt, puts in MOUNT_MENUS:
+ player('command', command='clear @s')
+ for item, _ in puts:
+ player('command', command=f'give @s {item}')
+ player('command', command=f'summon minecraft:{kind} {x + 0.5} {y} {z + 2.5} {nbt}')
+ player.wait(5)
+ found = [m for m in player.raw('mobs', 16).get('near', [])
+ if m['kind'].endswith(kind) and m['health'] > 0]
+ assert found, f'the {label} sees no {kind}'
+ mob = found[0]
+ p = mob['pos']
+ aim = (f'{p[0]:.2f}', f'{p[1] + HEIGHTS[kind] / 2:.2f}', f'{p[2]:.2f}')
+ try:
+ player.raw('look-at', *aim)
+ player.raw('key', 'shift', 'down')
+ player.wait(3)
+ player.raw('mouse', 'right', 'click')
+ player.wait(5)
+ player.raw('key', 'shift', 'up')
+ slots = mount_screen(player)
+ assert slots is not None, f"the {label}'s shift + right click on the {kind} opened no inventory"
+ for item, _ in puts:
+ player.raw('click-slot', hotbar_slot(player, item), 'shift')
+ player.wait(5)
+ slots = mount_screen(player)
+ for item, slot in puts:
+ assert slots.get(slot) == item, f"the {label}'s {kind}: {item} shift-clicked, slot {slot} holds {slots.get(slot)}"
+ player.raw('key', 'esc', 'tap')
+ player.wait(5)
+ for item, _ in puts:
+ left = server_count(player, item.split(':')[1])
+ assert left == 0, f'the server still counts {left} {item} on the {label}'
+ player.raw('look-at', *aim)
+ player.raw('mouse', 'right', 'click')
+ player.wait(8)
+ riding = player('status').get('riding')
+ assert riding == mob['id'], f'the {label} right-clicked its {kind}: riding {riding}'
+ player.raw('key', 'e', 'tap')
+ again = mount_screen(player)
+ assert again is not None, f'the inventory key on the {label}\'s {kind} opened no inventory'
+ for item, slot in puts:
+ assert again.get(slot) == item, f"the {label}'s {kind} reopened: slot {slot} holds {again.get(slot)}, not {item}"
+ player.raw('key', 'esc', 'tap')
+ player.wait(3)
+ hold(player, 'shift', 10)
+ player.wait(5)
+ result[label][kind] = {slot: item for item, slot in puts}
+ finally:
+ back_to_game(player)
+ player('command', command=f'kill @e[type=minecraft:{kind},x={x},y={y},z={z},distance=..16]')
+ player.wait(2)
+ player('command', command=f'kill @e[type=minecraft:item,x={x},y={y},z={z},distance=..16]')
+ player('command', command='clear @s')
+ player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0')
+ player.wait(5)
+ return result
+
+
def check_lightning(host, guest, out):
"""A bolt summoned beside each player: both sides get the bolt entity and flash the sky (the
host's window too on its server thread, FEATURES 4z(f))."""
@@ -3227,7 +3325,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast,
'light': check_light, 'plates': check_plates,
'swings': check_swings, 'cracks': check_cracks,
- 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding,
+ 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts,
'levels': check_levels}
diff --git a/tools/mod_browser_harness.py b/tools/mod_browser_harness.py
new file mode 100755
index 000000000..4531570bc
--- /dev/null
+++ b/tools/mod_browser_harness.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""End-to-end harness for Java mods from the launcher's mod browser (docs/mod-browser.md).
+
+ mod_browser_harness.py [--mod SLUG] [--query TEXT] [--keep]
+
+In a scratch game folder, as a player would through the Mods page (its CLI):
+
+1. `horizon-launcher mods search --kind mod TEXT` finds the mod on Modrinth;
+2. `horizon-launcher mods check SLUG` downloads its jar (checksum checked) and says Works or Partly;
+3. `horizon-launcher mods install SLUG` ports it into horizon-mods/ and turns it on;
+4. the game opens a survival world with it (horizon-ctl, offscreen), and
+5. a ported block item is given, held, and placed: the world then holds the mod's block;
+6. a ported recipe with vanilla ingredients is crafted on a crafting table: the result slot shows
+ the mod's item and taking it puts it in the inventory.
+
+It also times the install and the world's load with the mod against the same world with none
+(a ported mod must not slow a game that doesn't use it; this measures what one that does costs).
+Prints one JSON line per step and a summary; exits 1 when a step fails.
+
+Needs the launcher (launcher/target/debug/horizon-launcher, built with
+`--features gpui/runtime_shaders` on macOS), the game and horizon-ctl
+(target/fast/horizon-client, target/fast/horizon-ctl, or --bin DIR) and the prepared resources in
+.local/horizon-client/26.3. Downloads from Modrinth.
+"""
+import argparse
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class Failed(Exception):
+ pass
+
+
+def run(cmd, env, cwd=None, timeout=600):
+ p = subprocess.run(cmd, env=env, cwd=cwd, capture_output=True, text=True, timeout=timeout)
+ if p.returncode != 0:
+ raise Failed(f"{' '.join(map(str, cmd))}: exit {p.returncode}: {p.stderr.strip()[-800:] or p.stdout.strip()[-800:]}")
+ return p.stdout
+
+
+def report(step, **fields):
+ print(json.dumps({"step": step, **fields}), flush=True)
+
+
+class Game:
+ def __init__(self, ctl, client, resources, home, env):
+ self.ctl, self.client, self.resources, self.home, self.env = ctl, client, resources, home, env
+ self.socket = str(home / "ctl.sock")
+ self.pid = None
+
+ def __call__(self, *args, timeout=120):
+ out = run([self.ctl, "--socket", self.socket, "--timeout", str(timeout), *map(str, args)], self.env,
+ timeout=timeout + 30)
+ return json.loads(out.strip().splitlines()[-1])
+
+ def launch(self, world):
+ start = time.monotonic()
+ state = self("launch", "--game", self.client, "--world", world, "--seed", "1234", "--wait", "--offscreen",
+ "--resources", self.resources, timeout=300)
+ self.pid = state.get("launch", {}).get("pid")
+ return time.monotonic() - start, state
+
+ def quit(self):
+ try:
+ self("quit", timeout=30)
+ except Exception:
+ pass
+ if self.pid:
+ for _ in range(50):
+ try:
+ os.kill(self.pid, 0)
+ except OSError:
+ break
+ time.sleep(0.2)
+ else:
+ os.kill(self.pid, 9)
+ self.pid = None
+
+
+def resources_loaded(log):
+ """Seconds the game's log says its resources took."""
+ m = re.findall(r"resources loaded in ([0-9.]+)s", Path(log).read_text(errors="replace"))
+ return float(m[-1]) if m else None
+
+
+def pick_block(mod):
+ """A block the carry declares with its item."""
+ for f in sorted((mod / "data").glob("*/horizon/block/*.json")):
+ decl = json.loads(f.read_text())
+ if decl.get("item", True):
+ return f"{f.parts[-4]}:{f.stem}"
+ raise Failed("the carry declares no block with an item")
+
+
+def pick_recipe(mod, ns):
+ """A crafting recipe of the mod's whose result is its own and whose ingredients are plain vanilla
+ item ids, shaped first."""
+ found = []
+ for f in sorted((mod / "data").glob("*/recipe/**/*.json")):
+ try:
+ r = json.loads(f.read_text())
+ except ValueError:
+ continue
+ result = (r.get("result") or {}).get("id", "")
+ if not result.startswith(ns + ":"):
+ continue
+ if r.get("type") == "minecraft:crafting_shaped":
+ keys = r.get("key", {})
+ if all(isinstance(v, str) and v.startswith("minecraft:") for v in keys.values()) and \
+ len(r["pattern"]) <= 3 and all(len(row) <= 3 for row in r["pattern"]):
+ found.append((0, f.name, r))
+ elif r.get("type") == "minecraft:crafting_shapeless":
+ ing = r.get("ingredients", [])
+ if ing and len(ing) <= 9 and all(isinstance(v, str) and v.startswith("minecraft:") for v in ing):
+ found.append((1, f.name, r))
+ if not found:
+ raise Failed("no crafting recipe of the mod's with vanilla ingredients")
+ return sorted(found, key=lambda x: (x[0], x[1]))[0][2]
+
+
+def grid_cells(recipe):
+ """(slot, item) for each grid cell of a 3x3 crafting table (slots 100-108)."""
+ if recipe["type"] == "minecraft:crafting_shaped":
+ return [(100 + 3 * y + x, recipe["key"][c]) for y, row in enumerate(recipe["pattern"])
+ for x, c in enumerate(row) if c != " "]
+ return [(100 + i, item) for i, item in enumerate(recipe["ingredients"])]
+
+
+def inventory_slot(game, item):
+ inv = game("inventory")
+ for s in inv["hotbar"] + inv["main"]:
+ if s.get("item") == item:
+ return s["slot"]
+ raise Failed(f"{item} is not in the inventory: {inv.get('counts')}")
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--mod", default="macaws-fences-and-walls", help="Modrinth slug of a Works or Partly mod")
+ ap.add_argument("--query", default="macaw", help="the search text that finds it")
+ ap.add_argument("--launcher", default=str(ROOT / "launcher/target/debug/horizon-launcher"))
+ ap.add_argument("--bin", default=str(ROOT / "target/fast"), help="folder with horizon-client and horizon-ctl")
+ ap.add_argument("--resources", default=str(ROOT / ".local/horizon-client/26.3"))
+ ap.add_argument("--keep", action="store_true", help="keep the scratch game folder")
+ 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"))
+ launcher = [args.launcher]
+ game = Game(str(Path(args.bin) / "horizon-ctl"), str(Path(args.bin) / "horizon-client"),
+ args.resources, home, env)
+ summary = {"mod": args.mod}
+ ok = False
+ try:
+ # A baseline world first, with no mod: the same world's load time with the mod is compared.
+ base_home = home / "vanilla"
+ base_home.mkdir()
+ base = Game(game.ctl, game.client, args.resources, base_home,
+ dict(env, HORIZON_HOME=str(base_home), HORIZON_CONTROL=str(base_home / "ctl.sock")))
+ base.socket = str(base_home / "ctl.sock")
+ os.chdir(base_home)
+ took, _ = base.launch("browser")
+ summary["world_load_without_mods_s"] = round(took, 2)
+ summary["resources_without_mods_s"] = resources_loaded(base_home / "ctl.log")
+ base.quit()
+
+ found = json.loads(run(launcher + ["--json", "mods", "search", "--kind", "mod", *args.query.split()], env))
+ slugs = [p["slug"] for p in found]
+ report("search", query=args.query, results=len(found), found=args.mod in slugs)
+ if args.mod not in slugs:
+ raise Failed(f"{args.mod} not in the results: {slugs[:10]}")
+
+ start = time.monotonic()
+ check = json.loads(run(launcher + ["--json", "mods", "check", args.mod], env).strip().splitlines()[-1])
+ summary["check_s"] = round(time.monotonic() - start, 2)
+ report("check", verdict=check["label"], summary=check["summary"], seconds=summary["check_s"])
+ if check["verdict"] not in ("works", "partly"):
+ raise Failed(f"{args.mod} doesn't run: {check['summary']}")
+
+ start = time.monotonic()
+ run(launcher + ["mods", "install", args.mod], env)
+ summary["install_s"] = round(time.monotonic() - start, 2)
+ mod_id = check["mod_id"]
+ mod = home / "horizon-mods" / mod_id
+ on = (home / "horizon-mods.txt").read_text()
+ report("install", folder=str(mod.relative_to(home)), turned_on=f"mod.{mod_id}:true" in on,
+ seconds=summary["install_s"])
+ if not (mod / "horizon-mod.toml").is_file() or f"mod.{mod_id}:true" not in on:
+ raise Failed("not installed or not turned on")
+
+ os.chdir(home)
+ took, state = game.launch("browser")
+ summary["world_load_with_mod_s"] = round(took, 2)
+ summary["resources_with_mod_s"] = resources_loaded(home / "ctl.log")
+ log = (home / "ctl.log").read_text(errors="replace")
+ loaded = "content from 1 mod(s)" in log
+ report("world", seconds=round(took, 2), content_loaded=loaded, screen=state.get("screen"))
+ if not loaded:
+ raise Failed("the game didn't load the mod's content")
+
+ x, y, z = (int(v // 1) for v in state["player"]["position"])
+ block = pick_block(mod)
+ game("command", "gamemode survival")
+ game("command", f"fill {x + 1} {y - 1} {z - 2} {x + 4} {y - 1} {z + 2} minecraft:stone")
+ game("command", f"fill {x + 1} {y} {z - 2} {x + 4} {y + 2} {z + 2} minecraft:air")
+ game("give", block, 1)
+ game("select", block)
+ held = game("state")["held"]
+ placed = game("place", x + 2, y, z, "--item", block)
+ at = game("block", x + 2, y, z)
+ report("place", block=block, held=held, placed=at.get("block"))
+ if at.get("block") != block:
+ raise Failed(f"placing {block} left {at.get('block')}")
+
+ recipe = pick_recipe(mod, mod_id)
+ result = recipe["result"]["id"]
+ # A server command: horizon-ctl's own setblock changes the client's world only.
+ game("command", f"setblock {x + 2} {y} {z + 2} minecraft:crafting_table")
+ cells = grid_cells(recipe)
+ game("select", 9)
+ game("interact", x + 2, y, z + 2)
+ if game("screen").get("craft_size") != 3:
+ raise Failed("the crafting table didn't open")
+ # One item at a time, picked up and put down with left clicks: quick right clicks can
+ # cross the server's answers and be dropped.
+ for slot, item in cells:
+ game("give", item, 1)
+ time.sleep(0.2)
+ game("click-slot", inventory_slot(game, item))
+ time.sleep(0.2)
+ game("click-slot", slot)
+ time.sleep(0.2)
+ screen = game("screen")
+ out = next((s for s in screen.get("slots", []) if s.get("slot") == 200), {})
+ report("craft", recipe=result, result_slot=out.get("item"), count=out.get("count"))
+ if out.get("item") != result:
+ raise Failed(f"the table shows {out.get('item')}, not {result}")
+ game("click-slot", 200, "shift")
+ time.sleep(0.3)
+ counts = game("inventory")["counts"]
+ report("crafted", inventory=counts.get(result, 0))
+ if counts.get(result, 0) < 1:
+ raise Failed(f"{result} didn't reach the inventory")
+ game("close")
+ ok = True
+ except Failed as e:
+ report("failed", why=str(e))
+ finally:
+ game.quit()
+ summary["ok"] = ok
+ print(json.dumps({"summary": summary}), flush=True)
+ if args.keep:
+ print(f"kept {home}", file=sys.stderr)
+ else:
+ shutil.rmtree(home, ignore_errors=True)
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/website/docs/modpacks.md b/website/docs/modpacks.md
index a4396392b..a1aa1e2ea 100644
--- a/website/docs/modpacks.md
+++ b/website/docs/modpacks.md
@@ -6,11 +6,11 @@ Java mod jars do not run in Horizon. Instead, the launcher reads a modpack, tell
## What the Modpacks page does
-Open **Modpacks** in the launcher.
+Open **Modpacks** in the launcher. (From the next launcher release, it is the **Modpacks** tab of the **Mods** page.)
-1. **Import a pack.** Choose **Import a pack file…** for a Modrinth `.mrpack` or a CurseForge zip, or **Import an instance folder…** for a Prism, MultiMC or CurseForge instance. The **Mods** page can also find a Modrinth modpack and import it for you (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)).
+1. **Import a pack.** Choose **Import a pack file…** for a Modrinth `.mrpack` or a CurseForge zip, or **Import an instance folder…** for a Prism, MultiMC or CurseForge instance. The **Mods** page can also find a Modrinth modpack and import it for you (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)). From the next launcher release it also ports it in the same step, so you can press **Play** right away.
2. **Read the coverage report.** For every mod in the pack it says **Ported**, **Partial**, **Not yet** or **Not needed**, with the reason. You can filter the list by status.
-3. **Port.** **Port N mods** gets the jars of the mods this computer can carry over today, and carries them over for the version you picked. It copies the jars from a folder you have, or downloads them from the pack's own links (or the same file from Modrinth's download network), and checks their hashes. Files that only CurseForge has need CurseForge's API key, so for those choose **Use jars from my instance…** and point it at your installed instance.
+3. **Port.** **Port N mods** gets the jars of the mods this computer can carry over today, and carries them over for the version you picked. It copies the jars from a folder you have, or downloads them from the pack's own links (or the same file from Modrinth's download network), and checks their hashes. CurseForge downloads are coming soon, so for files that only CurseForge has, choose **Use jars from my instance…** and point it at your installed instance.
4. **Play.** **Play with N mods** starts the game as the pack's own profile, with its own saves and options, and those mods on.
Nothing is uploaded or shared. The mod jars and what is made from them stay on your computer.
@@ -29,6 +29,10 @@ Nothing is uploaded or shared. The mod jars and what is made from them stay on y
So a pack is a list of mods, and today Horizon can bring over a part of that list. The coverage report is the honest answer for your pack.
+If two ported mods use the same namespace, the game can only load one of them. The launcher keeps the first, leaves the other off, and lists it under the pack.
+
+Measured on three packs: Vanilla Perfected (108 files) ports 2 mods, Slimes Adventure (105) ports 20, and All the Mods 10 (496) ports 42. Each opens a world, with no crash. Every ported mod is partial: its blocks, items, recipes and structures come over, its Java code doesn't. A world with All the Mods 10's 42 ported mods takes about 40 seconds to load, against about 5 without mods.
+
## Example: All the Mods 10
All the Mods 10 has 495 jars. Horizon's report sorts them: about 290 add content, 80 are libraries, and the rest are integrations, interface mods, tools and performance mods. A few dozen of the content mods carry over today. The measured numbers are in [docs/modpacks.md](https://github.com/ludovic111/horizon/blob/main/docs/modpacks.md).
diff --git a/website/docs/mods.md b/website/docs/mods.md
index bc8cb7232..4d6a21189 100644
--- a/website/docs/mods.md
+++ b/website/docs/mods.md
@@ -36,7 +36,17 @@ cargo horizon-mod run
The launcher's **Mods** page (launcher 0.17 and newer) searches [Modrinth](https://modrinth.com) for what Horizon can load: resource packs, Java shader packs and modpacks. Each result says how well it runs in Horizon (**Works**, **Partly**, or **Doesn't run**), and by default the page shows only what runs. **Install** downloads the file, checks it against the checksum Modrinth lists and refuses anything that does not match, then puts it in the right folder, with the packs it needs. **Update** and **Remove** are there too. A resource pack still has to be turned on in the game's Resource Packs screen, and a shader pack in Video, Shader Packs. A modpack is imported on the [Modpacks page](/docs/modpacks).
-The page cannot search CurseForge yet. Java mod jars are never offered, because they do not run. The same things work from a terminal: `horizon-launcher mods search`, `install`, `update` and `remove`.
+CurseForge support is coming soon: the page shows it, but doesn't search it yet. The same things work from a terminal: `horizon-launcher mods search`, `install`, `update` and `remove`.
+
+## Java mods from the Mods page (next launcher release)
+
+Java code does not run in Horizon, but much of what a mod adds is data: blocks, items, recipes, loot tables, tags, worldgen, textures. From the next launcher release, the Mods page also lists Fabric, NeoForge and Forge mods made for 26.3 and, before offering one, downloads its jar, checks it against Modrinth's checksum and reads it (without running it) to say what of it Horizon runs:
+
+- **Works**: the mod is only content, and all of it carries over.
+- **Partly**: its content carries over; the row lists what does not, such as machines and containers, mobs, blocks or items with behaviour of their own, recipe types of its own, or Mixins.
+- **Doesn't run**: there is nothing to carry over (performance mods, libraries, mods that are all code). It is not offered.
+
+**Install** brings the mod over into `horizon-mods` and turns it on; start the game again to load it. Blocks take the closest vanilla block's shape, hardness and sounds, so a carried-over block can break faster or slower than in Java. Most popular mods today are **Partly** or **Doesn't run**: the verdict is the honest answer for each one.
## Data packs