From fb4897ec0922d20a209498ee4cc0a35c1b893a97 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sat, 24 Oct 2026 22:10:05 +0200
Subject: [PATCH 01/88] Website: /mods/submit, the registry's submission form
Sign in with GitHub through the registry's service (no scope), then send
the file and its page; the service checks the file, stages it and opens the
pull request, and the page links to it or says what to fix. A file named
-. fills in its kind, id and version. Shader packs are
listed and disabled until Horizon's own format exists. Caddy sends
/api/mods/* to REGISTRY_UPSTREAM (unset: the form says it isn't open), and
"Submit yours" now leads here.
Co-Authored-By: Claude Opus 5.5
---
website/Caddyfile | 7 +++-
website/README.md | 6 ++-
website/build.mjs | 9 +++--
website/src/mods-submit.js | 80 ++++++++++++++++++++++++++++++++++++++
website/src/mods.js | 67 ++++++++++++++++++++++++++++++-
website/src/mods.test.mjs | 15 ++++++-
website/src/style.css | 12 ++++++
7 files changed, 187 insertions(+), 9 deletions(-)
create mode 100644 website/src/mods-submit.js
diff --git a/website/Caddyfile b/website/Caddyfile
index 60554fd20..fb96e836d 100644
--- a/website/Caddyfile
+++ b/website/Caddyfile
@@ -35,7 +35,12 @@
rewrite /benchmarks /benchmarks.html
@doc path_regexp doc ^/docs/([a-z-]+)$
rewrite @doc /docs/{re.doc.1}.html
- # The registry: /mods, and /mods/ baked at build time, else the list page, whose script shows a project
+ # The registry's submission service (crates/horizon-mod-registry), over Railway's private network. Unset, the
+ # form says it isn't open.
+ handle /api/mods/* {
+ reverse_proxy {$REGISTRY_UPSTREAM:127.0.0.1:9}
+ }
+ # The registry: /mods, /mods/submit and /mods/ baked at build time, else the list page, whose script shows a project
# published since.
rewrite /mods /mods.html
@mod {
diff --git a/website/README.md b/website/README.md
index 52e26ec61..2813ce6dd 100644
--- a/website/README.md
+++ b/website/README.md
@@ -29,7 +29,7 @@ src/style.css every style, on top of the tokens
src/main.js the home page: download buttons, recent releases, links, contributors, nav, tabs, lightbox, motion
src/chrome.js the light/dark switch, the phone menu and GitHub fetching, shared by the pages
src/releases-page.js the Releases page: the channel filter and the refresh from GitHub
-src/mods.js the registry's markup (list, project page), shared by build and page; mods-page.js: the filter, the search, the refresh
+src/mods.js the registry's markup (list, project page, submit form), shared by build and page; mods-page.js: the filter, the search, the refresh; mods-submit.js: the form's sign-in and sending
src/benchmarks-page.js the Benchmarks page: players' results from the telemetry server, the picker
src/bench.js the Benchmarks tables, shared by build and page
src/hardware.js the spec table estimates use (GPU TFLOPS and bandwidth, CPU single-thread score)
@@ -110,7 +110,9 @@ a Caddy stage serves `dist/` on `$PORT` with compression, cache headers, a stric
Content-Security-Policy and the 404 page. Its watch patterns also redeploy when the README
or `launcher/links.json` change on main. No variables are needed; an optional
`GITHUB_TOKEN` (read-only, public repos) lets the build bake the releases even when
-GitHub's anonymous rate limit is hit.
+GitHub's anonymous rate limit is hit. `REGISTRY_UPSTREAM`
+(`horizon-mod-registry.railway.internal:8080`) sends `/api/mods/*` to the registry's submission
+service (`crates/horizon-mod-registry`); unset, `/mods/submit` says the form isn't open.
## Rules the site keeps
diff --git a/website/build.mjs b/website/build.mjs
index 0a813063b..8a6e04abe 100644
--- a/website/build.mjs
+++ b/website/build.mjs
@@ -16,7 +16,7 @@ import { machinesHtml, playersHtml } from "./src/bench.js";
import { CPUS, GPUS, singleThread } from "./src/hardware.js";
import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js";
import { contributorsFrom, contributorsHtml } from "./src/contributors.js";
-import { INDEX_URL, KINDS, SUBMIT, listHtml, projectHtml, readIndex } from "./src/mods.js";
+import { INDEX_URL, KINDS, SUBMIT, listHtml, projectHtml, readIndex, submitHtml } from "./src/mods.js";
const site = dirname(fileURLToPath(import.meta.url));
const dist = join(site, "dist");
@@ -186,7 +186,7 @@ await writeFile(join(dist, "favicon.ico"), Buffer.concat([ico, png32]));
const names = {};
const rewrite = (code) => code.replace(/"\.\/(\w+\.js)"/g, (all, file) => (names[file] ? `"./${names[file]}"` : all));
// Dependencies before what imports them.
-const modules = ["markdown.js", "versions.js", "chrome.js", "hardware.js", "estimate.js", "releases.js", "contributors.js", "bench.js", "main.js", "releases-page.js", "benchmarks-page.js", "mods.js", "mods-page.js"];
+const modules = ["markdown.js", "versions.js", "chrome.js", "hardware.js", "estimate.js", "releases.js", "contributors.js", "bench.js", "main.js", "releases-page.js", "benchmarks-page.js", "mods.js", "mods-page.js", "mods-submit.js"];
for (const file of modules) {
const code = rewrite(await readFile(join(site, "src", file), "utf8"));
names[file] = `${file.replace(".js", "")}.${fingerprint(code)}.js`;
@@ -401,7 +401,8 @@ ${listHtml(modProjects)}
`;
const modPages = [
{ file: "mods.html", path: "/mods", title: "Mods", description: "Mods, modpacks and resource packs made for Horizon, reviewed, each with what it may do and how to install it.", main: modsList },
- ...modProjects.map((p) => ({ file: `mods/${p.id}.html`, path: `/mods/${p.id}`, title: p.name, description: p.summary || p.name, main: projectHtml(p) })),
+ { file: "mods/submit.html", path: "/mods/submit", title: "Submit to the registry", description: "Submit a mod, a modpack or a resource pack made for Horizon: it is checked, reviewed, then listed here and in the launcher.", main: submitHtml(), js: "mods-submit.js" },
+ ...modProjects.filter((p) => p.id !== "submit").map((p) => ({ file: `mods/${p.id}.html`, path: `/mods/${p.id}`, title: p.name, description: p.summary || p.name, main: projectHtml(p) })),
];
await mkdir(join(dist, "mods"), { recursive: true });
const modsData = JSON.stringify(modIndex && modProjects.length ? { schema: modIndex.schema, projects: modProjects } : null).replace(/ form.elements.namedItem(name);
+
+function signedOut(message) {
+ auth.innerHTML = `${message}
Sign in with GitHub
It only reads your public profile: your GitHub name goes on the pull request and in the project's owners.
`;
+ form.hidden = true;
+}
+
+async function start() {
+ let me;
+ try {
+ const r = await fetch(`${API}/me`, { credentials: "same-origin" });
+ if (r.status === 401) return signedOut("Sign in to submit: reviewers and updates go through your GitHub account.");
+ if (!r.ok) throw new Error(String(r.status));
+ me = await r.json();
+ } catch {
+ auth.innerHTML = `The form isn't open right now. You can open a pull request by hand .
`;
+ return;
+ }
+ csrf = me.csrf;
+ auth.innerHTML = `Signed in as ${escape(me.login)} . Sign out
`;
+ document.getElementById("sign-out").addEventListener("click", async () => {
+ await fetch(`${API}/auth/logout`, { method: "POST", credentials: "same-origin" });
+ signedOut("Signed out.");
+ });
+ form.hidden = false;
+}
+
+// A file named -. fills in the two fields and the kind.
+form.querySelector("#f-file").addEventListener("change", (e) => {
+ const name = e.target.files[0]?.name || "";
+ const m = name.match(/^([a-z0-9_]{1,64})-([A-Za-z0-9][A-Za-z0-9._-]*)\.(hmod|hpack|zip)$/);
+ const kind = { hmod: "mod", hpack: "modpack", zip: "resourcepack" }[name.split(".").pop()];
+ if (kind) control("kind").value = kind;
+ if (m) {
+ if (!control("id").value) control("id").value = m[1];
+ if (!control("version").value) control("version").value = m[2];
+ }
+});
+
+form.addEventListener("submit", async (e) => {
+ e.preventDefault();
+ const send = form.querySelector("#f-send");
+ const values = Object.fromEntries(["id", "kind", "name", "summary", "description", "authors", "license", "source", "icon", "key", "version", "game", "changelog"].map((k) => [k, control(k).value]));
+ const sig = form.querySelector("#f-signature").files[0];
+ values.signature = sig ? await sig.text() : "";
+ const body = new FormData();
+ body.append("entry", JSON.stringify(entryFrom(values)));
+ body.append("file", form.querySelector("#f-file").files[0]);
+ send.disabled = true;
+ result.innerHTML = `Checking the file and opening the pull request…
`;
+ try {
+ const r = await fetch(`${API}/submit`, { method: "POST", body, credentials: "same-origin", headers: { "X-CSRF-Token": csrf } });
+ const json = await r.json().catch(() => ({}));
+ if (r.ok && /^https:\/\/github\.com\//.test(json.pull_request || "")) {
+ result.innerHTML = `Submitted. Follow the review in its pull request : the checks' report is there, and reviewers answer there.
`;
+ form.reset();
+ } else {
+ result.innerHTML = `${escape(json.error || `The service answered ${r.status}.`)}
`;
+ }
+ } catch {
+ result.innerHTML = `The service didn't answer. Try again in a minute.
`;
+ } finally {
+ send.disabled = false;
+ }
+});
+
+setUpTheme();
+setUpMenu();
+start();
diff --git a/website/src/mods.js b/website/src/mods.js
index 236a376ab..4819af374 100644
--- a/website/src/mods.js
+++ b/website/src/mods.js
@@ -5,7 +5,9 @@ import { markdown, escape } from "./markdown.js";
export const INDEX_URL = "https://ludovic111.github.io/horizon-mods/index.json";
const REGISTRY = "https://github.com/ludovic111/horizon-mods";
-export const SUBMIT = `${REGISTRY}#submit`;
+export const SUBMIT = "/mods/submit";
+// The submission form's service (crates/horizon-mod-registry), behind the site's own address.
+export const API = "/api/mods";
export const SCHEMA = 1;
// The kinds the site shows, in the filter's order. Kinds a newer index adds are left out until the site knows them.
@@ -108,3 +110,66 @@ export function projectHtml(p) {
Report it→
`;
}
+
+// /mods/submit: the form. Its script (mods-submit.js) signs in, then sends the page and the file to the service, which
+// checks the file and opens the pull request the reviewers read.
+const field = (name, label, input, hint = "") =>
+ `${label} ${input}${hint ? `${hint} ` : ""} `;
+const text = (name, attrs = "") => ` `;
+
+export function submitHtml() {
+ return `Mods Submit
+ Submit to the registry
+ A mod, a modpack of registry mods, or a resource pack made for Horizon. The form checks the file and opens a pull request; a reviewer reads it, its source and the checks' report, and merging publishes it to this site and the launcher.
+
+ `;
+}
+
+// The service's "entry" from the form's values (strings), as it reads it.
+export function entryFrom(v) {
+ const optional = (x) => (x && x.trim() ? x.trim() : undefined);
+ return {
+ id: v.id.trim(),
+ kind: v.kind,
+ name: v.name.trim(),
+ summary: v.summary.trim(),
+ description: v.description || "",
+ authors: (v.authors || "").split(",").map((a) => a.trim()).filter(Boolean),
+ license: v.license.trim(),
+ source: v.source.trim(),
+ icon: optional(v.icon),
+ key: optional(v.key),
+ signature: optional(v.signature),
+ version: v.version.trim(),
+ game: v.game.trim(),
+ changelog: v.changelog || "",
+ };
+}
diff --git a/website/src/mods.test.mjs b/website/src/mods.test.mjs
index 8dc5c0867..75e3ca4c5 100644
--- a/website/src/mods.test.mjs
+++ b/website/src/mods.test.mjs
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { CAPABILITIES, listHtml, matches, projectHtml, readIndex } from "./mods.js";
+import { CAPABILITIES, entryFrom, listHtml, matches, projectHtml, readIndex, submitHtml } from "./mods.js";
const project = (over = {}) => ({
id: "coords_hud", kind: "mod", name: "Coordinates HUD", summary: "Where you are.", authors: ["Horizon"],
@@ -40,3 +40,16 @@ test("a mod's page says what it may do, as the game does", () => {
assert.ok(projectHtml(project({ key: "RWT" })).includes("Signed"));
assert.ok(html.includes("horizon-launcher mods install --source horizon coords_hud"));
});
+
+test("the submit form sends what the service reads", () => {
+ const html = submitHtml();
+ for (const name of ["kind", "file", "id", "version", "game", "name", "summary", "license", "source", "key", "signature"]) {
+ assert.ok(html.includes(`id="f-${name}"`), name);
+ }
+ assert.match(html, //);
+ const entry = entryFrom({ id: " my_mod ", kind: "mod", name: "My mod", summary: "s", description: "", authors: "Alice, , Bob", license: "MIT", source: "https://x.test", icon: " ", key: "", signature: "", version: "1.0.0", game: "26.3", changelog: "" });
+ assert.deepEqual(entry.authors, ["Alice", "Bob"]);
+ assert.equal(entry.id, "my_mod");
+ assert.equal(entry.icon, undefined);
+ assert.equal(JSON.parse(JSON.stringify(entry)).key, undefined, "an empty key isn't sent");
+});
diff --git a/website/src/style.css b/website/src/style.css
index c67c9f8e4..c6a2d4b62 100644
--- a/website/src/style.css
+++ b/website/src/style.css
@@ -783,6 +783,18 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou
.mod-file dt { color: var(--muted); }
.mod-file code, .mod-steps code { font-family: var(--mono); font-size: 13px; overflow-wrap: anywhere; }
.mod-links { display: flex; flex-wrap: wrap; gap: 24px; margin-top: 24px; }
+/* /mods/submit */
+.mod-form { display: grid; gap: 24px; max-width: var(--measure); margin-top: 32px; }
+.mod-form fieldset { display: grid; gap: 16px; margin: 0; padding: 0; border: 0; }
+.mod-form legend { padding: 0; margin-bottom: 8px; }
+.mod-field { display: grid; gap: 6px; }
+.mod-label { font-size: var(--text-ui); font-weight: 500; }
+.mod-form .mod-search { width: 100%; }
+.mod-form textarea.mod-search { height: auto; padding: 10px 12px; line-height: 1.5; resize: vertical; }
+.mod-check { display: flex; gap: 10px; align-items: flex-start; font-size: var(--text-ui); }
+.mod-auth { margin-top: 24px; }
+.mod-error { color: var(--danger); font-size: var(--text-ui); }
+.js .no-script { display: none; }
@media (max-width: 640px) {
.mod-row { grid-template-columns: 40px minmax(0, 1fr); }
.mod-side { grid-column: 2; justify-items: start; }
From 7e513d2d5c85eefdf4b23d3e1295699e45cc4886 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sat, 24 Oct 2026 22:47:37 +0200
Subject: [PATCH 02/88] Launcher: Horizon's registry as a mod browser source
A browser source for Horizon's own registry (docs/api/mod-index.md): it reads index.json
(HORIZON_MOD_INDEX for a test registry, cached in the game folder for when the registry can't
be reached), searches it by kind and words, lists versions with the SHA-256 the index gives,
and blocks the versions it says were taken down. Downloads accept the registry's release host
and check SHA-256; file:// files only from a local index.
Installing, the takedown check before play and the CLI come next.
Co-Authored-By: Claude Opus 5.5
---
launcher/Cargo.lock | 9 +
launcher/Cargo.toml | 2 +
launcher/src/browser.rs | 40 +++-
launcher/src/browser/curseforge.rs | 1 +
launcher/src/browser/download.rs | 41 +++-
launcher/src/browser/horizon.rs | 280 ++++++++++++++++++++++++
launcher/src/browser/horizon/tests.rs | 61 ++++++
launcher/src/browser/installed/tests.rs | 1 +
launcher/src/browser/java.rs | 1 +
launcher/src/browser/modrinth.rs | 1 +
launcher/src/browser/tests.rs | 4 +-
11 files changed, 423 insertions(+), 18 deletions(-)
create mode 100644 launcher/src/browser/horizon.rs
create mode 100644 launcher/src/browser/horizon/tests.rs
diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock
index 5155420e0..a416a39ff 100644
--- a/launcher/Cargo.lock
+++ b/launcher/Cargo.lock
@@ -2673,6 +2673,7 @@ dependencies = [
"horizon-bench",
"horizon-core",
"horizon-friends",
+ "horizon-mods",
"horizon-port-pack",
"horizon-prepare",
"horizon-release-sign",
@@ -2698,8 +2699,10 @@ name = "horizon-mods"
version = "0.1.0"
dependencies = [
"log",
+ "minisign-verify",
"serde",
"serde_json",
+ "sha2 0.10.9",
"toml 1.1.8+spec-1.1.0",
"zip",
]
@@ -3470,6 +3473,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+[[package]]
+name = "minisign-verify"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
+
[[package]]
name = "miniz_oxide"
version = "0.8.9"
diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml
index a402d0e28..cfe9787d6 100644
--- a/launcher/Cargo.toml
+++ b/launcher/Cargo.toml
@@ -31,6 +31,8 @@ horizon-friends = { path = "../crates/horizon-friends" }
horizon-bench = { path = "../crates/horizon-bench" }
# Import modpack: the porting pipeline, run on the player's own files (docs/modpacks.md).
horizon-port-pack = { path = "../crates/horizon-port-pack" }
+# Horizon's mod registry: its index and the checks a download passes before install.
+horizon-mods = { path = "../crates/horizon-mods", features = ["index"] }
# Signed updates: archives are checked against the release's signed checksums (docs/security.md).
horizon-release-sign = { path = "../crates/horizon-release-sign" }
# Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md).
diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs
index f02638db5..7f81d5e37 100644
--- a/launcher/src/browser.rs
+++ b/launcher/src/browser.rs
@@ -8,6 +8,7 @@
pub mod curseforge;
pub mod details;
pub mod download;
+pub mod horizon;
pub mod images;
pub mod installed;
pub mod java;
@@ -56,6 +57,8 @@ impl Kind {
pub enum SourceId {
Modrinth,
CurseForge,
+ /// Horizon's own registry of reviewed mods, modpacks and resource packs ([`horizon`]).
+ Horizon,
}
impl SourceId {
@@ -63,6 +66,7 @@ impl SourceId {
match self {
SourceId::Modrinth => "Modrinth",
SourceId::CurseForge => "CurseForge",
+ SourceId::Horizon => "Horizon",
}
}
}
@@ -132,6 +136,8 @@ pub struct FileRef {
pub name: String,
pub size: u64,
pub sha512: Option,
+ /// What Horizon's registry lists.
+ pub sha256: Option,
pub sha1: Option,
pub primary: bool,
}
@@ -139,11 +145,13 @@ pub struct FileRef {
impl FileRef {
/// The strongest checksum the source gives: what the download is checked against.
pub fn checksum(&self) -> Option<(&'static str, &str)> {
- match (&self.sha512, &self.sha1) {
- (Some(h), _) => Some(("SHA-512", h)),
- (None, Some(h)) => Some(("SHA-1", h)),
- (None, None) => None,
- }
+ [
+ ("SHA-512", &self.sha512),
+ ("SHA-256", &self.sha256),
+ ("SHA-1", &self.sha1),
+ ]
+ .into_iter()
+ .find_map(|(algo, h)| Some((algo, h.as_deref()?)))
}
}
@@ -230,10 +238,11 @@ pub trait Source: Send + Sync {
/// What the launcher says wherever CurseForge would be.
pub const CURSEFORGE_SOON: &str = "CurseForge support is coming soon.";
-/// The sources this launcher uses: Modrinth. CurseForge support is coming soon: its API needs a
-/// paid key, so no search or install goes to it; `curseforge` is kept for then.
+/// The sources this launcher uses: Modrinth and Horizon's registry. CurseForge support is coming
+/// soon: its API needs a paid key, so no search or install goes to it; `curseforge` is kept for
+/// then.
pub fn sources() -> Vec> {
- vec![Box::new(modrinth::Modrinth)]
+ vec![Box::new(modrinth::Modrinth), Box::new(horizon::Registry)]
}
/// The source of that id, when this launcher can use it.
@@ -243,6 +252,15 @@ pub fn source(id: SourceId) -> Option> {
/// How well a project of `kind` made for `game_versions` and `loaders` runs in Horizon.
pub fn support(kind: Kind, game_versions: &[String], loaders: &[String]) -> Support {
+ if loaders.iter().any(|l| l == horizon::LOADER) {
+ // Made for Horizon and reviewed: it runs when it is for the version Horizon plays.
+ return match newest_release(game_versions)
+ .filter(|_| !game_versions.iter().any(|v| v == GAME))
+ {
+ Some(other) => Support::No(format!("Made for Horizon on {other}.")),
+ None => Support::Works,
+ };
+ }
match kind {
Kind::ResourcePack => {
if game_versions.iter().any(|v| v == GAME) {
@@ -309,6 +327,12 @@ pub fn pick(kind: Kind, versions: &[Version], everything: bool) -> Option<&Versi
let mut usable = versions
.iter()
.filter(|v| v.blocked.is_none() && v.file().is_some());
+ if versions
+ .iter()
+ .any(|v| v.loaders.iter().any(|l| l == horizon::LOADER))
+ {
+ return usable.find(|v| v.game_versions.iter().any(|g| g == GAME));
+ }
if kind == Kind::Mod {
let java = |v: &&Version| {
v.loaders
diff --git a/launcher/src/browser/curseforge.rs b/launcher/src/browser/curseforge.rs
index 4894fe5f0..e17a6b822 100644
--- a/launcher/src/browser/curseforge.rs
+++ b/launcher/src/browser/curseforge.rs
@@ -164,6 +164,7 @@ pub(super) fn parse_file(f: &Value) -> Option {
name: name.clone(),
size: f["fileLength"].as_u64().unwrap_or(0),
sha512: None,
+ sha256: None,
sha1,
primary: true,
}]
diff --git a/launcher/src/browser/download.rs b/launcher/src/browser/download.rs
index 66199fd07..593273245 100644
--- a/launcher/src/browser/download.rs
+++ b/launcher/src/browser/download.rs
@@ -1,16 +1,18 @@
//! Downloads that reach the game folder only when their checksum matches the source's.
use super::{safe_name, FileRef};
use sha1::Sha1;
-use sha2::{Digest, Sha512};
+use sha2::{Digest, Sha256, Sha512};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
-/// Hosts a file may come from: Modrinth's and CurseForge's file servers.
-const HOSTS: [&str; 3] = [
+/// Hosts a file may come from: Modrinth's and CurseForge's file servers, and the release assets
+/// of Horizon's registry.
+const HOSTS: [&str; 4] = [
"https://cdn.modrinth.com/",
"https://edge.forgecdn.net/",
"https://mediafilez.forgecdn.net/",
+ horizon_mods::index::FILE_HOST,
];
/// Bigger than any pack these sources serve (Modrinth caps uploads at 500 MiB).
const MAX: u64 = 1 << 30;
@@ -31,10 +33,15 @@ pub(super) fn agent() -> ureq::Agent {
pub fn refuse(file: &FileRef) -> Option {
if !HOSTS.iter().any(|h| file.url.starts_with(h)) {
return Some(format!(
- "{} isn't on Modrinth's or CurseForge's file servers.",
+ "{} isn't on Modrinth's, CurseForge's or Horizon's file servers.",
file.url
));
}
+ refuse_file(file)
+}
+
+/// [`refuse`] without the host: the name, the checksum and the size.
+fn refuse_file(file: &FileRef) -> Option {
if safe_name(&file.name).is_none() {
return Some(format!("{:?} isn't a plain file name.", file.name));
}
@@ -50,26 +57,29 @@ pub fn refuse(file: &FileRef) -> Option {
/// Hashes as they are written: the strongest one the file lists.
enum Hasher {
Sha512(Sha512),
+ Sha256(Sha256),
Sha1(Sha1),
}
impl Hasher {
fn for_file(file: &FileRef) -> Self {
- if file.sha512.is_some() {
- Hasher::Sha512(Sha512::new())
- } else {
- Hasher::Sha1(Sha1::new())
+ match file.checksum() {
+ Some(("SHA-512", _)) => Hasher::Sha512(Sha512::new()),
+ Some(("SHA-256", _)) => Hasher::Sha256(Sha256::new()),
+ _ => Hasher::Sha1(Sha1::new()),
}
}
fn update(&mut self, bytes: &[u8]) {
match self {
Hasher::Sha512(h) => h.update(bytes),
+ Hasher::Sha256(h) => h.update(bytes),
Hasher::Sha1(h) => h.update(bytes),
}
}
fn hex(self) -> String {
let bytes: Vec = match self {
Hasher::Sha512(h) => h.finalize().to_vec(),
+ Hasher::Sha256(h) => h.finalize().to_vec(),
Hasher::Sha1(h) => h.finalize().to_vec(),
};
bytes.iter().map(|b| format!("{b:02x}")).collect()
@@ -81,13 +91,26 @@ impl Hasher {
/// `progress` gets the fraction done.
pub fn save(
file: &FileRef,
- mut reader: impl Read,
+ reader: impl Read,
folder: &Path,
progress: &dyn Fn(f32),
) -> Result {
if let Some(why) = refuse(file) {
return Err(why);
}
+ save_from_anywhere(file, reader, folder, progress)
+}
+
+/// [`save`] for a file that comes from no host: a local test registry's.
+pub(super) fn save_from_anywhere(
+ file: &FileRef,
+ mut reader: impl Read,
+ folder: &Path,
+ progress: &dyn Fn(f32),
+) -> Result {
+ if let Some(why) = refuse_file(file) {
+ return Err(why);
+ }
let (algo, want) = file.checksum().expect("refuse checks for one");
fs::create_dir_all(folder).map_err(|e| format!("{}: {e}", folder.display()))?;
let target = folder.join(&file.name);
diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs
new file mode 100644
index 000000000..a54bca17f
--- /dev/null
+++ b/launcher/src/browser/horizon.rs
@@ -0,0 +1,280 @@
+//! Horizon's own registry (docs/api/mod-index.md): mods, modpacks and resource packs made for
+//! Horizon, reviewed as pull requests in ludovic111/horizon-mods. One file lists them all,
+//! `index.json`: this is the browser source that searches it and downloads its files, checked
+//! against the SHA-256 it lists. Versions the index says were taken down are blocked.
+use super::{
+ details::{Details, Link},
+ download, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME,
+};
+use horizon_mods::index::{self, Index};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+/// Where the registry publishes its index (GitHub Pages of ludovic111/horizon-mods).
+pub const INDEX_URL: &str = "https://ludovic111.github.io/horizon-mods/index.json";
+/// The registry's pages on the website, `/`.
+const SITE: &str = "https://playhorizon.dev/mods";
+/// The report form of a project.
+const REPORT: &str = "https://github.com/ludovic111/horizon-mods/issues/new?template=report.yml";
+/// The loader name the browser gives registry versions, so `support` and `pick` know them.
+pub const LOADER: &str = "horizon";
+/// How long a fetched index is used before it is fetched again.
+const FRESH: Duration = Duration::from_secs(600);
+/// Larger than any index should be.
+const MAX_INDEX: u64 = 16 << 20;
+/// The last index fetched, kept in the game folder for when the registry can't be reached.
+const CACHE: &str = "mod-browser/horizon-index.json";
+
+/// Where the index comes from: `HORIZON_MOD_INDEX` (a file or an `https://` address, for a
+/// test registry), else [`INDEX_URL`].
+fn location() -> String {
+ std::env::var("HORIZON_MOD_INDEX")
+ .ok()
+ .filter(|v| !v.is_empty())
+ .unwrap_or_else(|| INDEX_URL.to_owned())
+}
+
+/// True when the index is a local file: its files may then be local too (`file://`), for
+/// trying a registry out before it is published.
+pub fn local() -> bool {
+ !location().starts_with("https://")
+}
+
+static LOADED: Mutex)>> = Mutex::new(None);
+
+/// The index: the one fetched in the last ten minutes, else fetched again (and kept in the game
+/// folder), else the copy kept last time.
+pub fn index() -> Result, String> {
+ if let Some((at, index)) = LOADED.lock().unwrap().as_ref() {
+ if at.elapsed() < FRESH {
+ return Ok(index.clone());
+ }
+ }
+ let cache = crate::backend::game_home().join(CACHE);
+ let index = match fetch_index() {
+ Ok((index, text)) => {
+ if let Some(dir) = cache.parent() {
+ let _ = fs::create_dir_all(dir);
+ }
+ let _ = fs::write(&cache, text);
+ index
+ }
+ Err(e) => {
+ let kept = fs::read_to_string(&cache).map_err(|_| e.clone())?;
+ match local() {
+ true => Index::parse_local(&kept),
+ false => Index::parse(&kept),
+ }
+ .map_err(|_| e)?
+ }
+ };
+ let index = Arc::new(index);
+ *LOADED.lock().unwrap() = Some((Instant::now(), index.clone()));
+ Ok(index)
+}
+
+fn fetch_index() -> Result<(Index, String), String> {
+ use std::io::Read;
+ let at = location();
+ let text = if at.starts_with("https://") {
+ let response = download::agent().get(&at).call().map_err(|e| match e {
+ ureq::Error::Status(code, _) => format!("The mod registry answered {code}."),
+ ureq::Error::Transport(t) => format!("The mod registry can't be reached: {t}"),
+ })?;
+ let mut text = String::new();
+ response
+ .into_reader()
+ .take(MAX_INDEX)
+ .read_to_string(&mut text)
+ .map_err(|e| e.to_string())?;
+ text
+ } else {
+ fs::read_to_string(&at).map_err(|e| format!("{at}: {e}"))?
+ };
+ let index = match local() {
+ true => Index::parse_local(&text)?,
+ false => Index::parse(&text)?,
+ };
+ Ok((index, text))
+}
+
+/// The browser's kind for a registry kind; None for one the launcher doesn't install yet
+/// (Horizon modpacks and shader packs, kinds newer than this launcher).
+fn kind_of(kind: &index::Kind) -> Option {
+ match kind {
+ index::Kind::Mod => Some(Kind::Mod),
+ index::Kind::ResourcePack => Some(Kind::ResourcePack),
+ index::Kind::Modpack | index::Kind::Shader | index::Kind::Other(_) => None,
+ }
+}
+
+fn project_of(p: &index::Project) -> Option {
+ let mut game_versions: Vec = p.versions.iter().map(|v| v.game.clone()).collect();
+ game_versions.dedup();
+ Some(Project {
+ source: SourceId::Horizon,
+ id: p.id.clone(),
+ slug: p.id.clone(),
+ title: p.name.clone(),
+ summary: p.summary.clone(),
+ author: p.authors.join(", "),
+ downloads: 0,
+ page: format!("{SITE}/{}", p.id),
+ icon: p.icon.clone(),
+ license: p.license.clone(),
+ kind: kind_of(&p.kind)?,
+ game_versions,
+ loaders: vec![LOADER.into()],
+ })
+}
+
+fn version_of(index: &Index, p: &index::Project, v: &index::Version) -> Version {
+ Version {
+ id: v.version.clone(),
+ number: v.version.clone(),
+ published: v.published.clone(),
+ game_versions: vec![v.game.clone()],
+ loaders: vec![LOADER.into()],
+ files: vec![FileRef {
+ url: v.file.url.clone(),
+ name: v.file.name.clone(),
+ size: v.file.size,
+ sha512: None,
+ sha256: Some(v.file.sha256.clone()),
+ sha1: None,
+ primary: true,
+ }],
+ required: v.requires.iter().map(|r| r.id.clone()).collect(),
+ blocked: index
+ .revoked(&p.id, &v.file.sha256)
+ .map(|r| format!("taken down: {}", r.reason)),
+ }
+}
+
+/// The words of a query found in a project's id, name, summary or authors.
+fn matches(p: &index::Project, text: &str) -> bool {
+ let hay = format!("{} {} {} {}", p.id, p.name, p.summary, p.authors.join(" ")).to_lowercase();
+ text.split_whitespace()
+ .all(|word| hay.contains(&word.to_lowercase()))
+}
+
+/// The projects of the query's kind whose words match, for this game unless `everything`.
+fn search(index: &Index, query: &Query) -> Vec {
+ index
+ .projects
+ .iter()
+ .filter(|p| kind_of(&p.kind) == Some(query.kind) && matches(p, &query.text))
+ .filter(|p| query.everything || p.versions.iter().any(|v| v.game == GAME))
+ .filter_map(project_of)
+ .skip(query.offset)
+ .take(query.limit)
+ .collect()
+}
+
+/// The registry as a browser source.
+pub struct Registry;
+
+impl Source for Registry {
+ fn id(&self) -> SourceId {
+ SourceId::Horizon
+ }
+
+ fn search(&self, query: &Query) -> Result, String> {
+ Ok(search(&*index()?, query))
+ }
+
+ fn project(&self, id: &str) -> Result {
+ let index = index()?;
+ let p = index
+ .project(id)
+ .ok_or_else(|| format!("{id} isn't in Horizon's registry."))?;
+ project_of(p).ok_or_else(|| {
+ format!(
+ "{} is a {} in Horizon's registry: this launcher can't install those yet.",
+ p.name,
+ p.kind.name()
+ )
+ })
+ }
+
+ fn versions(&self, project: &Project) -> Result, String> {
+ let index = index()?;
+ let p = index
+ .project(&project.id)
+ .ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?;
+ Ok(p.versions
+ .iter()
+ .map(|v| version_of(&index, p, v))
+ .collect())
+ }
+
+ fn details(&self, project: &Project) -> Result {
+ let index = index()?;
+ let p = index
+ .project(&project.id)
+ .ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?;
+ let newest = p.versions.first();
+ let mut body = p.description.clone();
+ if let Some(v) = newest.filter(|v| !v.capabilities.is_empty()) {
+ body.push_str("\n\n## What it may do\n\n");
+ for c in &v.capabilities {
+ body.push_str(&format!("- May {}\n", c.describe()));
+ }
+ }
+ Ok(Details {
+ body,
+ links: vec![
+ Link {
+ label: "Source".into(),
+ url: p.source.clone(),
+ },
+ Link {
+ label: "Page".into(),
+ url: project.page.clone(),
+ },
+ Link {
+ label: "Report".into(),
+ url: format!("{REPORT}&title={}", p.id),
+ },
+ ],
+ authors: p.authors.clone(),
+ published: p
+ .versions
+ .last()
+ .map(|v| v.published.clone())
+ .unwrap_or_default(),
+ updated: newest.map(|v| v.published.clone()).unwrap_or_default(),
+ ..Details::default()
+ })
+ }
+
+ fn fetch(
+ &self,
+ file: &FileRef,
+ folder: &Path,
+ progress: &dyn Fn(f32),
+ ) -> Result {
+ fetch(file, folder, local(), progress)
+ }
+}
+
+/// Downloads a registry file, checked; `file://` files only from a local index.
+fn fetch(
+ file: &FileRef,
+ folder: &Path,
+ local: bool,
+ progress: &dyn Fn(f32),
+) -> Result {
+ match file.url.strip_prefix("file://").filter(|_| local) {
+ Some(path) => {
+ let reader = fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
+ download::save_from_anywhere(file, reader, folder, progress)
+ }
+ None => download::fetch(file, folder, progress),
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/launcher/src/browser/horizon/tests.rs b/launcher/src/browser/horizon/tests.rs
new file mode 100644
index 000000000..1ca0cf3ee
--- /dev/null
+++ b/launcher/src/browser/horizon/tests.rs
@@ -0,0 +1,61 @@
+//! The registry source against the sample index of `horizon_mods::index`
+//! (`crates/horizon-mods/tests/index/`), its files served from disk.
+use super::*;
+
+fn fixtures() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../crates/horizon-mods/tests/index")
+}
+
+/// The sample index with its files on disk, as a local test registry lists them.
+fn sample() -> Index {
+ let text = fs::read_to_string(fixtures().join("index-v1.json")).unwrap();
+ let mut index = Index::parse(&text).unwrap();
+ for p in &mut index.projects {
+ for v in &mut p.versions {
+ let path = fixtures().join(&v.file.name);
+ v.file.url = format!("file://{}", path.canonicalize().unwrap_or(path).display());
+ }
+ }
+ index
+}
+
+fn hud(index: &Index) -> Project {
+ project_of(index.project("coords_hud").unwrap()).unwrap()
+}
+
+#[test]
+fn searches_by_kind_and_words() {
+ let index = sample();
+ let found = |text: &str, kind| -> Vec {
+ search(&index, &Query::new(text, kind))
+ .into_iter()
+ .map(|p| p.id)
+ .collect()
+ };
+ assert_eq!(found("", Kind::Mod), ["coords_hud"]);
+ assert_eq!(found("coordinates HUD", Kind::Mod), ["coords_hud"]);
+ assert!(found("zoom", Kind::Mod).is_empty());
+ // Kinds this launcher can't install yet (modpacks, a world) are never offered.
+ assert!(found("", Kind::Modpack).is_empty());
+ assert!(found("skyblock", Kind::ResourcePack).is_empty());
+ let p = hud(&index);
+ assert_eq!(p.support(), super::super::Support::Works);
+ assert_eq!(p.page, "https://playhorizon.dev/mods/coords_hud");
+}
+
+#[test]
+fn registry_versions_run_when_made_for_this_game() {
+ use super::super::{pick, support, Support};
+ let v = |game: &str| vec![game.to_owned()];
+ let horizon = vec![LOADER.to_owned()];
+ assert_eq!(support(Kind::Mod, &v(GAME), &horizon), Support::Works);
+ assert!(!support(Kind::Mod, &v("26.2"), &horizon).installable());
+ let index = sample();
+ let p = index.project("coords_hud").unwrap();
+ let versions: Vec = p
+ .versions
+ .iter()
+ .map(|x| version_of(&index, p, x))
+ .collect();
+ assert_eq!(pick(Kind::Mod, &versions, false).unwrap().number, "0.1.0");
+}
diff --git a/launcher/src/browser/installed/tests.rs b/launcher/src/browser/installed/tests.rs
index e940ce0f1..cb2814c29 100644
--- a/launcher/src/browser/installed/tests.rs
+++ b/launcher/src/browser/installed/tests.rs
@@ -86,6 +86,7 @@ impl Fake {
.map(|b| format!("{b:02x}"))
.collect(),
),
+ sha256: None,
sha1: None,
primary: true,
};
diff --git a/launcher/src/browser/java.rs b/launcher/src/browser/java.rs
index 76ce43c95..62122d1f5 100644
--- a/launcher/src/browser/java.rs
+++ b/launcher/src/browser/java.rs
@@ -326,6 +326,7 @@ mod tests {
name: "a.jar".into(),
size: 1,
sha512: sha512.map(str::to_owned),
+ sha256: None,
sha1: sha1.map(str::to_owned),
primary: true,
};
diff --git a/launcher/src/browser/modrinth.rs b/launcher/src/browser/modrinth.rs
index 722549742..52e0aa7f0 100644
--- a/launcher/src/browser/modrinth.rs
+++ b/launcher/src/browser/modrinth.rs
@@ -139,6 +139,7 @@ pub(super) fn parse_version(v: &Value) -> Option {
name: f["filename"].as_str()?.to_owned(),
size: f["size"].as_u64().unwrap_or(0),
sha512: f["hashes"]["sha512"].as_str().map(str::to_ascii_lowercase),
+ sha256: None,
sha1: f["hashes"]["sha1"].as_str().map(str::to_ascii_lowercase),
primary: f["primary"].as_bool().unwrap_or(false),
})
diff --git a/launcher/src/browser/tests.rs b/launcher/src/browser/tests.rs
index 6167d5bd9..50bfbae40 100644
--- a/launcher/src/browser/tests.rs
+++ b/launcher/src/browser/tests.rs
@@ -18,6 +18,7 @@ fn version(id: &str, games: &[&str], loaders: &[&str]) -> Version {
name: format!("{id}.zip"),
size: 3,
sha512: Some("ab".into()),
+ sha256: None,
sha1: None,
primary: true,
}],
@@ -305,6 +306,7 @@ fn file_for(body: &[u8], sha512: bool) -> FileRef {
name: "pack.zip".into(),
size: body.len() as u64,
sha512: sha512.then(|| hex(&sha2::Sha512::digest(body))),
+ sha256: None,
sha1: (!sha512).then(|| hex(&sha1::Sha1::digest(body))),
primary: true,
}
@@ -383,6 +385,6 @@ fn live_modrinth_search_pick_and_download() {
#[test]
fn curseforge_is_coming_soon_and_never_searched() {
let ids: Vec = sources().iter().map(|s| s.id()).collect();
- assert_eq!(ids, [SourceId::Modrinth]);
+ assert_eq!(ids, [SourceId::Modrinth, SourceId::Horizon]);
assert!(source(SourceId::CurseForge).is_none());
}
From b49fd602df9dd5ebe00fa23bfd5316390544d729 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sat, 24 Oct 2026 22:47:51 +0200
Subject: [PATCH 03/88] Launcher: install from Horizon's registry, enable and
disable, takedowns
Mods install into horizon-mods/.hmod (turned on) and resource packs into
resourcepacks/, each downloaded to mod-browser/downloads/ and checked by
horizon_mods::index::check_file (size, SHA-256, signature, manifest) before it
is moved into place. Files the index takes down are turned off when the index
is read or the game starts, and can't be installed or turned back on. CLI (and
so MCP): --source horizon, mods enable|disable, and search shows whether a
project is signed and what a mod may do.
Co-Authored-By: Claude Opus 5.5
---
docs/launcher-commands.md | 26 +++-
docs/mod-browser.md | 19 +++
launcher/src/backend.rs | 1 +
launcher/src/browser/horizon.rs | 202 +++++++++++++++++++++++++-
launcher/src/browser/horizon/tests.rs | 84 +++++++++++
launcher/src/browser/installed.rs | 8 +-
launcher/src/browser/java.rs | 10 ++
launcher/src/cli.rs | 52 ++++++-
8 files changed, 393 insertions(+), 9 deletions(-)
diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md
index 9dc4382f4..7c9562441 100644
--- a/docs/launcher-commands.md
+++ b/docs/launcher-commands.md
@@ -323,7 +323,7 @@ Search for packs Horizon loads.
- `TEXT`
- `--kind` (mod, resource, modpack)
- `--everything`: Also what was made for other versions or runs only partly, each marked
-- `--source` (modrinth, curseforge)
+- `--source` (modrinth, curseforge, horizon)
MCP: `mods_search`.
@@ -335,7 +335,7 @@ Say how well a Java mod runs in Horizon: its jar is downloaded (checksum checked
- `PROJECT`
- `--everything`: Allow a version made for another Minecraft version (1.21 and later)
-- `--source` (modrinth, curseforge)
+- `--source` (modrinth, curseforge, horizon)
MCP: `mods_check`.
@@ -347,7 +347,7 @@ Install a pack and what it needs, by its id or slug (checksums checked); a Java
- `PROJECT`
- `--everything`: Allow a version made for another Minecraft version
-- `--source` (modrinth, curseforge)
+- `--source` (modrinth, curseforge, horizon)
MCP: `mods_install`.
@@ -372,6 +372,26 @@ Remove a pack the browser installed.
MCP: `mods_remove`, needs `confirm: true`.
+## `horizon-launcher mods enable`
+
+Turn on a mod the browser installed (horizon-mods.txt, as the game's Options > Mods does).
+
+ horizon-launcher mods enable
+
+- `PROJECT`
+
+MCP: `mods_enable`.
+
+## `horizon-launcher mods disable`
+
+Turn off a mod the browser installed; it stays installed.
+
+ horizon-launcher mods disable
+
+- `PROJECT`
+
+MCP: `mods_disable`.
+
## `horizon-launcher servers list`
The servers, their folder and whether they run.
diff --git a/docs/mod-browser.md b/docs/mod-browser.md
index 7a000cb6c..6c961fd42 100644
--- a/docs/mod-browser.md
+++ b/docs/mod-browser.md
@@ -149,6 +149,25 @@ horizon-launcher mods remove faithful-32x
## Sources
+**Horizon's registry.** Mods (`.hmod`) and resource packs made for Horizon, reviewed as pull requests in
+[ludovic111/horizon-mods](https://github.com/ludovic111/horizon-mods) ([api/mod-index.md](api/mod-index.md)). The
+launcher reads its `index.json` (`browser/horizon.rs`; `HORIZON_MOD_INDEX=` reads a test
+registry instead, whose files may then be on disk) at most every ten minutes, and keeps the last copy in
+`mod-browser/horizon-index.json`. Before a result is installed it shows whether its files are signed and, for a mod,
+what it may do, in the words of the game's Options > Mods. A download goes to `mod-browser/downloads/` and is moved
+into place only after `horizon_mods::index::check_file` passes (size, SHA-256, the author's signature when the project
+has a key, the file's own manifest against the index). A mod becomes `horizon-mods/.hmod`, turned on;
+`mods disable` and `mods enable` switch it in `horizon-mods.txt`. When the index takes a file down, the launcher turns
+it off the next time it reads the index or starts the game, says why, and refuses to install it or turn it back on.
+Horizon modpacks (`.hpack`) and shader packs are listed by the index but not installed by this launcher yet.
+
+```sh
+horizon-launcher mods search --source horizon --kind mod coords # with whether it is signed and what it may do
+horizon-launcher mods install --source horizon coords_hud
+horizon-launcher mods disable coords_hud
+```
+
+
**Modrinth.** The public API (`api.modrinth.com/v2`) needs no key. The launcher names itself in its user agent, as
Modrinth asks.
diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs
index 104a086a5..957994f16 100644
--- a/launcher/src/backend.rs
+++ b/launcher/src/backend.rs
@@ -1636,6 +1636,7 @@ pub fn need_prepared(tag: &str) -> Result<(), String> {
pub fn client(tag: &str) -> Result {
need_prepared(tag)?;
complete_packs(tag);
+ crate::browser::horizon::before_play(&game_home());
let mut cmd = client_command(tag);
// A sign-in that can't be renewed (no network, expired) still lets the game start, offline.
if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) {
diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs
index a54bca17f..53e426ab0 100644
--- a/launcher/src/browser/horizon.rs
+++ b/launcher/src/browser/horizon.rs
@@ -1,12 +1,13 @@
//! Horizon's own registry (docs/api/mod-index.md): mods, modpacks and resource packs made for
//! Horizon, reviewed as pull requests in ludovic111/horizon-mods. One file lists them all,
-//! `index.json`: this is the browser source that searches it and downloads its files, checked
-//! against the SHA-256 it lists. Versions the index says were taken down are blocked.
+//! `index.json`; every download is checked against it before it reaches the game folder
+//! (`horizon_mods::index::check_file`: size, SHA-256, the author's signature, the file's own
+//! manifest), and files the index says were taken down are refused and turned off.
use super::{
details::{Details, Link},
- download, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME,
+ download, installed, java, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME,
};
-use horizon_mods::index::{self, Index};
+use horizon_mods::index::{self, Index, Trust};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
@@ -110,6 +111,32 @@ fn kind_of(kind: &index::Kind) -> Option {
}
}
+/// What the player reads about a registry project before installing it: whether its files are
+/// signed, and for a mod what it may do, in the game's words (Options > Mods).
+pub fn trust_and_capabilities(id: &str) -> Vec {
+ let Ok(index) = index() else {
+ return Vec::new();
+ };
+ let Some(p) = index.project(id) else {
+ return Vec::new();
+ };
+ let mut lines = vec![match &p.key {
+ Some(_) => "Signed by its author: the launcher checks the signature".to_owned(),
+ None => "Unsigned: the launcher checks its checksum only".to_owned(),
+ }];
+ if let Some(v) = p.versions.first().filter(|_| p.kind == index::Kind::Mod) {
+ lines.extend(
+ v.capabilities
+ .iter()
+ .map(|c| format!("May {}", c.describe())),
+ );
+ if v.capabilities.is_empty() {
+ lines.push("Asks for nothing beyond its own log".into());
+ }
+ }
+ lines
+}
+
fn project_of(p: &index::Project) -> Option {
let mut game_versions: Vec = p.versions.iter().map(|v| v.game.clone()).collect();
game_versions.dedup();
@@ -276,5 +303,172 @@ fn fetch(
}
}
+/// What the registry adds to an installed entry.
+fn trust_label(trust: Trust) -> &'static str {
+ match trust {
+ Trust::Verified => "Verified",
+ Trust::Unsigned => "Unsigned",
+ }
+}
+
+/// The game folder path a registry project's file goes to.
+fn relative(kind: Kind, id: &str, file_name: &str) -> Result {
+ match kind {
+ Kind::Mod => Ok(format!("{}/{id}.hmod", java::MODS_DIR)),
+ Kind::ResourcePack => Ok(format!("resourcepacks/{file_name}")),
+ Kind::Modpack => {
+ Err("Modpacks from Horizon's registry install from the Modpacks page.".into())
+ }
+ }
+}
+
+/// Installs a registry project into the game folder `home`: its newest version for this game,
+/// downloaded into `mod-browser/downloads/`, checked against the index, then moved into place.
+/// A mod is `horizon-mods/.hmod`, turned on in `horizon-mods.txt`.
+pub fn install(
+ project: &Project,
+ home: &Path,
+ progress: &dyn Fn(&str, f32),
+) -> Result, String> {
+ install_from(&*index()?, local(), project, home, progress)
+}
+
+fn install_from(
+ index: &Index,
+ local: bool,
+ project: &Project,
+ home: &Path,
+ progress: &dyn Fn(&str, f32),
+) -> Result, String> {
+ let p = index
+ .project(&project.id)
+ .ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?;
+ let v = p
+ .versions
+ .iter()
+ .find(|v| v.game == GAME && index.revoked(&p.id, &v.file.sha256).is_none())
+ .ok_or_else(|| format!("{} has no version for {GAME} to install.", project.title))?;
+ let relative = relative(project.kind, &p.id, &v.file.name)?;
+ let mut list = installed::Installed::load(home);
+ let ours = |e: &installed::Entry| e.source == SourceId::Horizon && e.project == p.id;
+ let old = list.entries.iter().find(|e| ours(e)).cloned();
+ if old.as_ref().is_some_and(|o| o.version == v.version) {
+ return Ok(vec![old.expect("checked")]);
+ }
+ let target = home.join(&relative);
+ let taken_by = list.entries.iter().find(|e| !ours(e) && e.file == relative);
+ let folder_mod = home.join(java::MODS_DIR).join(&p.id);
+ if let Some(other) = taken_by {
+ return Err(format!(
+ "{relative} belongs to {}: remove it first.",
+ other.title
+ ));
+ }
+ if (target.exists() && old.as_ref().is_none_or(|o| o.file != relative)) || folder_mod.exists() {
+ return Err(format!(
+ "A mod with the id {} is already in {}: move it away first.",
+ p.id,
+ java::MODS_DIR
+ ));
+ }
+ let line = format!("{} {}", p.name, v.version);
+ let file = &version_of(index, p, v).files[0];
+ let staging = home.join("mod-browser/downloads");
+ let path = fetch(file, &staging, local, &|f| progress(&line, f))?;
+ let trust = index::check_file(index, p, v, &path).inspect_err(|_| {
+ let _ = fs::remove_file(&path);
+ })?;
+ if let Some(dir) = target.parent() {
+ fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ }
+ fs::rename(&path, &target).map_err(|e| format!("{}: {e}", target.display()))?;
+ if let Some(old) = old.as_ref().filter(|o| o.file != relative) {
+ let _ = fs::remove_file(home.join(&old.file));
+ }
+ if project.kind == Kind::Mod {
+ java::set_enabled(home, &p.id, true)?;
+ }
+ let entry = installed::Entry {
+ source: SourceId::Horizon,
+ project: p.id.clone(),
+ slug: p.id.clone(),
+ title: p.name.clone(),
+ kind: project.kind,
+ version: v.version.clone(),
+ number: v.version.clone(),
+ file: relative,
+ checksum: format!("SHA-256:{}", v.file.sha256),
+ page: project.page.clone(),
+ dependency: false,
+ verdict: Some(trust_label(trust).into()),
+ skipped: Vec::new(),
+ namespaces: Vec::new(),
+ };
+ list.entries.retain(|e| !ours(e));
+ list.entries.push(entry.clone());
+ list.save(home)?;
+ Ok(vec![entry])
+}
+
+/// The mod id of an installed mod (`horizon-mods/` or `horizon-mods/.hmod`).
+pub fn mod_id(entry: &installed::Entry) -> Option<&str> {
+ let rest = entry.file.strip_prefix(java::MODS_DIR)?.strip_prefix('/')?;
+ Some(rest.strip_suffix(".hmod").unwrap_or(rest))
+}
+
+/// Turns the registry's files that were taken down off in the game folder `home`, and says
+/// which. Their files stay, so the player sees them and can remove them.
+pub fn turn_off_revoked(index: &Index, home: &Path) -> Vec {
+ let mut out = Vec::new();
+ for e in installed::Installed::load(home).entries {
+ let hash = e.checksum.strip_prefix("SHA-256:").unwrap_or_default();
+ let Some(r) = (e.source == SourceId::Horizon)
+ .then(|| index.revoked(&e.project, hash))
+ .flatten()
+ else {
+ continue;
+ };
+ if let (Kind::Mod, Some(id)) = (e.kind, mod_id(&e)) {
+ if java::is_enabled(home, id) && java::set_enabled(home, id, false).is_ok() {
+ out.push(format!(
+ "{} was taken down and is off: {}",
+ e.title, r.reason
+ ));
+ }
+ } else if e.kind == Kind::ResourcePack {
+ out.push(format!(
+ "{} was taken down: {} Remove it.",
+ e.title, r.reason
+ ));
+ }
+ }
+ out
+}
+
+/// Before the game starts: registry files taken down are turned off, by the index kept last
+/// time (no waiting on the network), and the index is fetched again in the background for the
+/// next start. Nothing happens when nothing came from the registry.
+pub fn before_play(home: &Path) {
+ let from_registry = installed::Installed::load(home)
+ .entries
+ .iter()
+ .any(|e| e.source == SourceId::Horizon);
+ if !from_registry {
+ return;
+ }
+ let kept = fs::read_to_string(home.join(CACHE)).ok();
+ if let Some(index) = kept.and_then(|t| Index::parse(&t).ok()) {
+ for line in turn_off_revoked(&index, home) {
+ eprintln!("{line}");
+ }
+ }
+ let home = home.to_owned();
+ std::thread::spawn(move || {
+ if let Ok(index) = index() {
+ turn_off_revoked(&index, &home);
+ }
+ });
+}
+
#[cfg(test)]
mod tests;
diff --git a/launcher/src/browser/horizon/tests.rs b/launcher/src/browser/horizon/tests.rs
index 1ca0cf3ee..b46d7061d 100644
--- a/launcher/src/browser/horizon/tests.rs
+++ b/launcher/src/browser/horizon/tests.rs
@@ -19,6 +19,16 @@ fn sample() -> Index {
index
}
+fn scratch(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "horizon-launcher-registry-{name}-{}",
+ std::process::id()
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
fn hud(index: &Index) -> Project {
project_of(index.project("coords_hud").unwrap()).unwrap()
}
@@ -43,6 +53,80 @@ fn searches_by_kind_and_words() {
assert_eq!(p.page, "https://playhorizon.dev/mods/coords_hud");
}
+#[test]
+fn installs_checked_turns_on_and_removes() {
+ let index = sample();
+ let home = scratch("install");
+ let p = hud(&index);
+ let done = install_from(&index, true, &p, &home, &|_, _| {}).unwrap();
+ assert_eq!(done[0].file, "horizon-mods/coords_hud.hmod");
+ assert_eq!(done[0].verdict.as_deref(), Some("Verified"));
+ assert!(done[0].checksum.starts_with("SHA-256:e1135345"));
+ assert!(home.join("horizon-mods/coords_hud.hmod").is_file());
+ let list = fs::read_to_string(home.join("horizon-mods.txt")).unwrap();
+ assert_eq!(list, "mod.coords_hud:true\n");
+ assert_eq!(
+ fs::read_dir(home.join("mod-browser/downloads"))
+ .unwrap()
+ .count(),
+ 0
+ );
+ // Installed already: nothing to do.
+ let again = install_from(&index, true, &p, &home, &|_, _| {}).unwrap();
+ assert_eq!(again, done);
+
+ let mut revoked = index.clone();
+ revoked.revoked.push(index::Revoked {
+ id: "coords_hud".into(),
+ sha256: None,
+ reason: "Test.".into(),
+ date: String::new(),
+ });
+ let said = turn_off_revoked(&revoked, &home);
+ assert_eq!(said, ["Coordinates HUD was taken down and is off: Test."]);
+ assert_eq!(
+ fs::read_to_string(home.join("horizon-mods.txt")).unwrap(),
+ ""
+ );
+
+ installed::remove(&home, "coords_hud").unwrap();
+ assert!(!home.join("horizon-mods/coords_hud.hmod").exists());
+ assert!(installed::Installed::load(&home).entries.is_empty());
+ fs::remove_dir_all(&home).unwrap();
+}
+
+#[test]
+fn refuses_a_changed_file_a_taken_id_and_local_files_from_the_real_registry() {
+ let index = sample();
+ let p = hud(&index);
+
+ let home = scratch("tampered");
+ let mut tampered = index.clone();
+ let cozy = tampered.projects[1].versions[0].file.url.clone();
+ tampered.projects[0].versions[0].file.url = cozy;
+ let e = install_from(&tampered, true, &p, &home, &|_, _| {}).unwrap_err();
+ assert!(e.contains("larger than its source says"), "{e}");
+ assert!(!home.join("horizon-mods").exists());
+
+ let e = install_from(&index, false, &p, &home, &|_, _| {}).unwrap_err();
+ assert!(e.contains("file servers"), "{e}");
+
+ fs::create_dir_all(home.join("horizon-mods/coords_hud")).unwrap();
+ let e = install_from(&index, true, &p, &home, &|_, _| {}).unwrap_err();
+ assert!(e.contains("already in horizon-mods"), "{e}");
+
+ let mut taken_down = index.clone();
+ taken_down.revoked.push(index::Revoked {
+ id: "coords_hud".into(),
+ sha256: Some(index.projects[0].versions[0].file.sha256.clone()),
+ reason: "Test.".into(),
+ date: String::new(),
+ });
+ let e = install_from(&taken_down, true, &p, &home, &|_, _| {}).unwrap_err();
+ assert!(e.contains("no version"), "{e}");
+ fs::remove_dir_all(&home).unwrap();
+}
+
#[test]
fn registry_versions_run_when_made_for_this_game() {
use super::super::{pick, support, Support};
diff --git a/launcher/src/browser/installed.rs b/launcher/src/browser/installed.rs
index 451bdd43e..c866dd26d 100644
--- a/launcher/src/browser/installed.rs
+++ b/launcher/src/browser/installed.rs
@@ -170,6 +170,9 @@ pub fn install(
home: &Path,
progress: &dyn Fn(&str, f32),
) -> Result, String> {
+ if project.source == SourceId::Horizon {
+ return super::horizon::install(project, home, progress);
+ }
if project.kind == Kind::Mod {
return super::java::install(source, project, everything, home, progress);
}
@@ -248,7 +251,7 @@ pub fn remove(home: &Path, name: &str) -> Result {
.lookup(name)
.cloned()
.ok_or_else(|| format!("{name} wasn't installed by the browser."))?;
- if entry.kind == Kind::Mod {
+ if entry.kind == Kind::Mod && entry.source != SourceId::Horizon {
super::java::remove(home, &entry)?;
} else {
match fs::remove_file(home.join(&entry.file)) {
@@ -257,6 +260,9 @@ pub fn remove(home: &Path, name: &str) -> Result {
Err(e) => return Err(format!("{}: {e}", entry.file)),
}
}
+ if let Some(id) = super::horizon::mod_id(&entry).filter(|_| entry.source == SourceId::Horizon) {
+ super::java::set_enabled(home, id, false)?;
+ }
installed
.entries
.retain(|e| !(e.source == entry.source && e.project == entry.project));
diff --git a/launcher/src/browser/java.rs b/launcher/src/browser/java.rs
index 62122d1f5..4ac7ae084 100644
--- a/launcher/src/browser/java.rs
+++ b/launcher/src/browser/java.rs
@@ -110,6 +110,16 @@ pub fn check_project(
Ok((version, check))
}
+/// Whether mod `id` is on in `horizon-mods.txt`.
+pub fn is_enabled(home: &Path, id: &str) -> bool {
+ let key = format!("mod.{id}");
+ fs::read_to_string(home.join(MODS_LIST))
+ .unwrap_or_default()
+ .lines()
+ .filter_map(|l| l.split_once(':'))
+ .any(|(k, v)| k.trim() == key && v.trim() == "true")
+}
+
/// Turns mod `id` on (or off) in `horizon-mods.txt`, keeping the other lines.
pub fn set_enabled(home: &Path, id: &str, on: bool) -> Result<(), String> {
let path = home.join(MODS_LIST);
diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs
index d104fe7eb..4dd5d2d20 100644
--- a/launcher/src/cli.rs
+++ b/launcher/src/cli.rs
@@ -199,6 +199,10 @@ enum ModsCmd {
},
/// Remove a pack the browser installed
Remove { project: String },
+ /// Turn on a mod the browser installed (horizon-mods.txt, as the game's Options > Mods does)
+ Enable { project: String },
+ /// Turn off a mod the browser installed; it stays installed
+ Disable { project: String },
}
#[derive(Clone, Copy, clap::ValueEnum)]
@@ -213,6 +217,8 @@ enum SourceArg {
Modrinth,
/// CurseForge support is coming soon
Curseforge,
+ /// Horizon's own registry: mods, modpacks and resource packs made for Horizon, reviewed
+ Horizon,
}
impl SourceArg {
@@ -221,6 +227,7 @@ impl SourceArg {
let id = match self {
SourceArg::Modrinth => SourceId::Modrinth,
SourceArg::Curseforge => SourceId::CurseForge,
+ SourceArg::Horizon => SourceId::Horizon,
};
browser::source(id).ok_or_else(|| browser::CURSEFORGE_SOON.into())
}
@@ -1064,11 +1071,23 @@ fn servers(action: ServersCmd, as_json: bool) -> Result<(), String> {
}
fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
- use horizon_launcher::browser::{installed, Kind, Query};
+ use horizon_launcher::browser::{horizon, installed, Kind, Query, SourceId};
use horizon_launcher::modpacks;
let home = backend::game_home();
let entry_json = |e: &installed::Entry| serde_json::to_value(e).unwrap_or_default();
let line = |label: &str, f: f32| progress(label.to_string())(f);
+ let from_registry = installed::Installed::load(&home)
+ .entries
+ .iter()
+ .any(|e| e.source == SourceId::Horizon);
+ if from_registry {
+ if let Ok(index) = horizon::index() {
+ for said in horizon::turn_off_revoked(&index, &home) {
+ eprintln!("{said}");
+ }
+ }
+ }
+ let on = matches!(action, ModsCmd::Enable { .. });
match action {
ModsCmd::List => {
let list = installed::Installed::load(&home).entries;
@@ -1114,11 +1133,19 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
"id": p.id, "slug": p.slug, "title": p.title, "summary": p.summary,
"author": p.author, "downloads": p.downloads, "page": p.page,
"license": p.license, "support": support.label(), "reason": support.reason(),
+ "about": if p.source == SourceId::Horizon { horizon::trust_and_capabilities(&p.id) } else { Vec::new() },
})
}).collect());
} else {
for p in &found {
let support = p.support();
+ if p.source == SourceId::Horizon {
+ println!("{} ({}) {}\n {}", p.title, p.slug, p.author, p.summary);
+ for line in horizon::trust_and_capabilities(&p.id) {
+ println!(" {line}");
+ }
+ continue;
+ }
let unchecked = p.kind == Kind::Mod && support.installable();
println!(
"{} ({}) {} · {} downloads\n {}",
@@ -1251,6 +1278,29 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
let e = installed::remove(&home, &project)?;
println!("Removed {} ({}).", e.title, e.file);
}
+ ModsCmd::Enable { project } | ModsCmd::Disable { project } => {
+ let e = installed::Installed::load(&home)
+ .lookup(&project)
+ .cloned()
+ .ok_or_else(|| format!("{project} wasn't installed by the browser."))?;
+ let id = horizon::mod_id(&e)
+ .filter(|_| e.kind == Kind::Mod)
+ .ok_or_else(|| format!("{} isn't a mod: only mods turn on and off.", e.title))?;
+ if on {
+ if let Some(r) = horizon::index()
+ .ok()
+ .filter(|_| e.source == SourceId::Horizon)
+ .and_then(|i| {
+ i.revoked(&e.project, e.checksum.trim_start_matches("SHA-256:"))
+ .cloned()
+ })
+ {
+ return Err(format!("{} was taken down: {}", e.title, r.reason));
+ }
+ }
+ horizon_launcher::browser::java::set_enabled(&home, id, on)?;
+ println!("{} is {}.", e.title, if on { "on" } else { "off" });
+ }
}
Ok(())
}
From f602ad6fe303ccd7aafe18514855b29c1dfa6058 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sat, 24 Oct 2026 21:33:42 +0200
Subject: [PATCH 04/88] Launcher Mods page: Horizon's registry beside Modrinth
The source switch now picks Modrinth or Horizon (CurseForge stays coming
soon). On Horizon each result says whether its files are signed and what
the mod may do, in the game's words, before Install; no Java check, no
download count, no Modrinth filters. Installed Horizon mods get an
on/off switch (horizon-mods.txt); one the registry took down is turned
off when the page reads the index and can't be turned back on.
Registry icons load from its GitHub Pages. HORIZON_LAUNCHER_SOURCE=horizon
opens the page on it, for screenshots.
Co-Authored-By: Claude Opus 5.5
---
launcher/src/browser/horizon.rs | 9 ++
launcher/src/browser/images.rs | 4 +-
launcher/src/mods_page.rs | 192 ++++++++++++++++++++++++++++----
launcher/src/mods_project.rs | 1 +
4 files changed, 184 insertions(+), 22 deletions(-)
diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs
index 53e426ab0..410fdd01e 100644
--- a/launcher/src/browser/horizon.rs
+++ b/launcher/src/browser/horizon.rs
@@ -45,6 +45,15 @@ pub fn local() -> bool {
static LOADED: Mutex)>> = Mutex::new(None);
+/// The index read last in this run, without asking the network: for what must not wait.
+pub fn known_index() -> Option> {
+ LOADED
+ .lock()
+ .unwrap()
+ .as_ref()
+ .map(|(_, index)| index.clone())
+}
+
/// The index: the one fetched in the last ten minutes, else fetched again (and kept in the game
/// folder), else the copy kept last time.
pub fn index() -> Result, String> {
diff --git a/launcher/src/browser/images.rs b/launcher/src/browser/images.rs
index fee2f219e..f5029a7af 100644
--- a/launcher/src/browser/images.rs
+++ b/launcher/src/browser/images.rs
@@ -9,10 +9,12 @@ use std::io::Read;
use std::path::{Path, PathBuf};
/// Hosts images may come from.
-const HOSTS: [&str; 3] = [
+const HOSTS: [&str; 4] = [
"https://cdn.modrinth.com/",
"https://media.forgecdn.net/",
"https://edge.forgecdn.net/",
+ // Horizon's registry's icons (its GitHub Pages).
+ "https://ludovic111.github.io/horizon-mods/",
];
/// The most an image may weigh before decoding.
pub const MAX_DOWNLOAD: u64 = 8 << 20;
diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs
index 86e5e2e48..5e60549a1 100644
--- a/launcher/src/mods_page.rs
+++ b/launcher/src/mods_page.rs
@@ -1,11 +1,13 @@
-//! The Mods page: search Modrinth (CurseForge: coming soon) for Java mods, modpacks and resource
-//! packs, see where each comes from and how well it runs (a Java mod's jar is
-//! checked first), install it with its checksum checked, and update or remove what was installed
-//! (`horizon_launcher::browser`). Imported modpacks are listed on its Modpacks tab.
+//! The Mods page: search Horizon's own registry for mods made for Horizon, or Modrinth
+//! (CurseForge: coming soon) for Java mods, modpacks and resource packs, see where each comes
+//! from and how well it runs (a Java mod's jar is checked first; a Horizon mod says whether it is
+//! signed and what it may do), install it with its checksum checked, turn Horizon mods on and
+//! off, and update or remove what was installed (`horizon_launcher::browser`). Imported modpacks
+//! are listed on its Modpacks tab.
use super::servers_page::{type_key, Key};
use super::*;
use horizon_launcher::browser::{
- self, installed, java, Kind as PackKind, Project, Query, SourceId, Support,
+ self, horizon, installed, java, Kind as PackKind, Project, Query, SourceId, Support,
};
use horizon_launcher::modpacks;
use horizon_port_pack::check::Check;
@@ -20,7 +22,10 @@ const KINDS: [(PackKind, &str, &str); 3] = [
/// Java mods checked at once.
const CHECKING: usize = 2;
/// The sources to pick from; CurseForge is shown beside them as coming soon.
-const SOURCES: [(SourceId, &str); 1] = [(SourceId::Modrinth, "Modrinth")];
+const SOURCES: [(SourceId, &str); 2] = [
+ (SourceId::Modrinth, "Modrinth"),
+ (SourceId::Horizon, "Horizon"),
+];
const PAGE: usize = 20;
pub(super) enum Event {
@@ -31,6 +36,10 @@ pub(super) enum Event {
Updates(HashMap<(SourceId, String), String>),
/// A Java mod's check: its jar read, or why it couldn't be.
Checked((SourceId, String), Result, String>),
+ /// What a Horizon registry project says before install: signed or not, what it may do.
+ About(HashMap>),
+ /// Registry files taken down that the launcher turned off.
+ TakenDown(Vec),
/// A project page's part, an image or a filter's values (`mods_project`).
Loaded(super::mods_project::Loaded),
}
@@ -68,6 +77,8 @@ pub(super) struct Mods {
confirm_remove: Option,
/// Java mods' checks, by source and project.
pub(super) checks: HashMap<(SourceId, String), Checking>,
+ /// Horizon registry projects' trust and capabilities, by id ([`horizon::trust_and_capabilities`]).
+ pub(super) about: HashMap>,
/// The project page, filters and images.
pub(super) browse: super::mods_project::Browse,
pub(super) tx: Sender,
@@ -94,7 +105,11 @@ impl Mods {
} else {
PackKind::Mod
},
- source: SourceId::Modrinth,
+ // `HORIZON_LAUNCHER_SOURCE=horizon` opens on Horizon's registry, for screenshots.
+ source: match std::env::var("HORIZON_LAUNCHER_SOURCE").as_deref() {
+ Ok("horizon") => SourceId::Horizon,
+ _ => SourceId::Modrinth,
+ },
text: String::new(),
focus: cx.focus_handle().tab_index(0).tab_stop(true),
focused: false,
@@ -115,6 +130,7 @@ impl Mods {
updates: HashMap::new(),
confirm_remove: None,
checks: HashMap::new(),
+ about: HashMap::new(),
browse: Default::default(),
tx,
rx,
@@ -134,7 +150,7 @@ impl Mods {
/// How well a result runs: a Java mod's from its check once it has one.
pub(super) fn support(&self, p: &Project) -> Support {
let metadata = p.support();
- if p.kind != PackKind::Mod || !metadata.installable() {
+ if p.kind != PackKind::Mod || p.source == SourceId::Horizon || !metadata.installable() {
return metadata;
}
match self.checks.get(&(p.source, p.id.clone())) {
@@ -231,6 +247,16 @@ impl Launcher {
m.checks.insert(key, state);
}
Event::Loaded(l) => loaded.push(l),
+ Event::About(about) => {
+ // Rows grow by a line: measure them again (`cull`).
+ m.about.extend(about);
+ m.results_list.reset();
+ }
+ Event::TakenDown(lines) => {
+ m.message = Some(Ok(lines.join("\n")));
+ m.installed = installed::Installed::load(&backend::game_home()).entries;
+ m.installed_list.reset();
+ }
}
}
// `HORIZON_LAUNCHER_PROJECT=` (with `HORIZON_LAUNCHER_PAGE=mods`): opens that
@@ -278,7 +304,63 @@ impl Launcher {
let result = browser::source(source)
.ok_or_else(|| format!("{} isn't set up.", source.label()))
.and_then(|s| s.search(&query));
+ let about: HashMap> = match (&result, source) {
+ (Ok(found), SourceId::Horizon) => found
+ .iter()
+ .map(|p| (p.id.clone(), horizon::trust_and_capabilities(&p.id)))
+ .collect(),
+ _ => HashMap::new(),
+ };
let _ = tx.send(Event::Found(search, offset, result));
+ if !about.is_empty() {
+ let _ = tx.send(Event::About(about));
+ }
+ });
+ }
+
+ /// Reads the registry's index again when something installed came from it, and turns off
+ /// what it took down since (`horizon::turn_off_revoked`).
+ fn mods_taken_down(&mut self) {
+ if !self
+ .mods
+ .installed
+ .iter()
+ .any(|e| e.source == SourceId::Horizon)
+ {
+ return;
+ }
+ let tx = self.mods.tx.clone();
+ std::thread::spawn(move || {
+ let Ok(index) = horizon::index() else {
+ return;
+ };
+ let lines = horizon::turn_off_revoked(&index, &backend::game_home());
+ if !lines.is_empty() {
+ let _ = tx.send(Event::TakenDown(lines));
+ }
+ });
+ }
+
+ /// Turns a Horizon mod the browser installed on or off, as the game's Options > Mods does.
+ fn mods_switch(&mut self, e: &installed::Entry) {
+ let home = backend::game_home();
+ let Some(id) = horizon::mod_id(e) else {
+ return;
+ };
+ let on = !java::is_enabled(&home, id);
+ let revoked = horizon::known_index().and_then(|index| {
+ let hash = e.checksum.trim_start_matches("SHA-256:");
+ index.revoked(&e.project, hash).map(|r| r.reason.clone())
+ });
+ self.mods.message = Some(match revoked.filter(|_| on) {
+ Some(reason) => Err(format!("{} was taken down: {reason}", e.title)),
+ None => java::set_enabled(&home, id, on).map(|()| {
+ format!(
+ "{} is {}. The game reads this when it starts.",
+ e.title,
+ if on { "on" } else { "off" }
+ )
+ }),
});
}
@@ -288,7 +370,8 @@ impl Launcher {
let m = &mut self.mods;
let todo: Vec = found
.into_iter()
- .filter(|p| p.kind == PackKind::Mod && p.support().installable())
+ .filter(|p| p.kind == PackKind::Mod && p.source != SourceId::Horizon)
+ .filter(|p| p.support().installable())
.filter(|p| !m.checks.contains_key(&(p.source, p.id.clone())))
.collect();
if todo.is_empty() {
@@ -403,6 +486,13 @@ impl Launcher {
.iter()
.map(|e| format!("{} {}", e.title, e.number))
.collect();
+ if p.source == SourceId::Horizon && p.kind == PackKind::Mod {
+ return Ok(format!(
+ "Installed {} into horizon-mods and turned it on, checksum checked \
+ (Options > Mods in the game).",
+ names.join(", ")
+ ));
+ }
if p.kind == PackKind::Mod {
let skipped = done.last().map_or(0, |e| e.skipped.len());
return Ok(format!(
@@ -497,14 +587,15 @@ impl Launcher {
self.mods.loaded = true;
self.mods.installed = installed::Installed::load(&backend::game_home()).entries;
self.mods_check_updates();
+ self.mods_taken_down();
self.mods_search(0);
}
let header = page_header(
"Mods",
- "Java mods, modpacks and resource packs. Horizon ports what a Java mod \
- carries (blocks, items, recipes, worldgen) and says before you install what runs. \
- Each file is checked against its source's checksum before it reaches your game \
- folder.",
+ "Mods made for Horizon from its own reviewed registry, and Java mods, modpacks and \
+ resource packs from Modrinth: Horizon ports what a Java mod carries (blocks, items, \
+ recipes, worldgen) and says before you install what runs. Each file is checked \
+ against its source's checksum before it reaches your game folder.",
&t,
);
let this = cx.entity().downgrade();
@@ -543,7 +634,10 @@ impl Launcher {
}));
// CurseForge support is coming soon: shown, inert, never searched (like the Microsoft
// account's "Coming soon").
- let source_note = div().flex().child(source_switch(&t));
+ let source_note = div().flex().child(self.mods_source_switch(cx));
+ // The registry lists only what was made for Horizon: no "everything", no Modrinth filters.
+ let registry = self.mods.source == SourceId::Horizon;
+ let filters = (!registry).then(|| self.mods_filters(cx));
let controls = div()
.flex()
.flex_col()
@@ -555,10 +649,10 @@ impl Launcher {
.items_center()
.gap(px(12.))
.child(self.mods_field(cx))
- .child(toggle),
+ .when(!registry, |d| d.child(toggle)),
)
.child(source_note)
- .child(self.mods_filters(cx));
+ .children(filters);
// The kinds are inventory tabs on the panel that holds the open one.
let body = blocks::panel(&t).flex().flex_col().gap(px(24.)).p(px(20.));
let page = |body: Div| {
@@ -687,6 +781,30 @@ impl Launcher {
}
cx.notify();
}));
+ if e.source == SourceId::Horizon && e.kind == PackKind::Mod {
+ let on = horizon::mod_id(e)
+ .is_some_and(|id| java::is_enabled(&backend::game_home(), id));
+ let entry = e.clone();
+ right = right.child(
+ div()
+ .id(SharedString::from(format!("mods-switch-{}", e.project)))
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .cursor_pointer()
+ // Its id sits under the row's own, so one name serves every row.
+ .child(switch("mods-switch-knob", on, &t))
+ .child(text(theme::LABEL).text_color(t.ink_soft).child(if on {
+ "On"
+ } else {
+ "Off"
+ }))
+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
+ this.mods_switch(&entry);
+ cx.notify();
+ })),
+ );
+ }
right = right.child(remove);
let detail = div()
.flex()
@@ -750,6 +868,8 @@ impl Launcher {
if m.results.is_empty() {
let line = if m.searching || !m.searched {
"Searching…"
+ } else if m.source == SourceId::Horizon {
+ "Nothing in Horizon's registry matches yet."
} else if m.everything {
"Nothing found."
} else {
@@ -768,6 +888,7 @@ impl Launcher {
let busy = m.busy.as_ref().map(|b| b.0.as_str());
let support = m.support(p);
let checking = p.kind == PackKind::Mod
+ && p.source != SourceId::Horizon
&& matches!(
m.checks.get(&(p.source, p.id.clone())),
None | Some(Checking::Running)
@@ -828,7 +949,9 @@ impl Launcher {
if !p.author.is_empty() {
by.push(format!("by {}", p.author));
}
- by.push(format!("{} downloads", count(p.downloads)));
+ if p.source != SourceId::Horizon {
+ by.push(format!("{} downloads", count(p.downloads)));
+ }
by.push(format!("from {}", p.source.label()));
if !p.license.is_empty() {
by.push(p.license.clone());
@@ -842,6 +965,12 @@ impl Launcher {
support
.reason()
.map(|r| div().text_color(t.ink_soft).child(r.to_string())),
+ )
+ .children(
+ m.about
+ .get(&p.id)
+ .filter(|_| p.source == SourceId::Horizon)
+ .map(|lines| div().text_color(t.ink_soft).child(lines.join(" · "))),
);
let open = p.clone();
let name = div()
@@ -884,9 +1013,30 @@ impl Launcher {
}
}
-/// The source switch while Modrinth is the only source: Modrinth chosen, CurseForge shown as
-/// coming soon and not clickable, like the Microsoft account's "Coming soon".
-fn source_switch(t: &Theme) -> Stateful {
+impl Launcher {
+ /// The source switch: Modrinth or Horizon's registry, CurseForge shown as coming soon and not
+ /// clickable, like the Microsoft account's "Coming soon".
+ fn mods_source_switch(&self, cx: &mut Context
) -> Stateful {
+ let this = cx.entity().downgrade();
+ source_switch(&self.theme, self.mods.source, move |source, _, cx| {
+ let _ = this.update(cx, |this, cx| {
+ if this.mods.source != source {
+ this.mods.source = source;
+ this.mods.browse.filters = Default::default();
+ this.mods.browse.open = None;
+ this.mods_search(0);
+ }
+ cx.notify();
+ });
+ })
+ }
+}
+
+fn source_switch(
+ t: &Theme,
+ current: SourceId,
+ on_pick: impl Fn(SourceId, &mut Window, &mut App) + Clone + 'static,
+) -> Stateful
{
let soon = div()
.flex()
.items_center()
@@ -899,7 +1049,7 @@ fn source_switch(t: &Theme) -> Stateful
{
.text_color(t.muted)
.child("CurseForge (coming soon)"),
);
- segments("mods-source", &SOURCES, SourceId::Modrinth, t, |_, _, _| {}).child(soon)
+ segments("mods-source", &SOURCES, current, t, on_pick).child(soon)
}
#[cfg(test)]
diff --git a/launcher/src/mods_project.rs b/launcher/src/mods_project.rs
index ad75f58cd..97d23e0aa 100644
--- a/launcher/src/mods_project.rs
+++ b/launcher/src/mods_project.rs
@@ -423,6 +423,7 @@ impl Launcher {
self.mods.checks.get(&(p.source, p.id.clone())),
None | Some(Checking::Running)
) && p.kind == PackKind::Mod
+ && p.source != SourceId::Horizon
&& p.support().installable();
let mut action = div().flex().items_center().gap(px(8.)).child(
caps(if checking {
From dbdc0389fe9ce9d46911f7f0b8bff12b83eb7607 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sat, 24 Oct 2026 22:25:02 +0200
Subject: [PATCH 05/88] Launcher: Horizon modpacks from the registry, each its
own profile
A registry modpack (.hpack) now shows under Modpacks with the Horizon
source, with its mods and what each may do, and installs into
horizon-packs/
/: the checked pack, pack.json and home/, where each of
its mods is downloaded and checked like any registry mod (pinned to the
pack's version and SHA-256) and turned on or off as the pack says. Its
overrides are copied on the first install only. A pack whose mod was taken
down installs nothing and leaves nothing behind. The Modpacks tab lists
installed registry packs with Play and Remove (confirmed); they play through
modpacks::apply_profile with their own HORIZON_HOME, taken-down mods turned
off first. CLI: `mods install --source horizon `, and `modpack
list|play|remove` see registry packs.
Co-Authored-By: Claude Opus 5.5
---
docs/mod-browser.md | 9 +-
launcher/src/browser/horizon.rs | 65 ++++--
launcher/src/browser/horizon/pack.rs | 294 ++++++++++++++++++++++++++
launcher/src/browser/horizon/tests.rs | 4 +-
launcher/src/cli.rs | 40 +++-
launcher/src/main.rs | 3 +
launcher/src/modpacks.rs | 8 +
launcher/src/modpacks_page.rs | 80 +++++++
launcher/src/mods_page.rs | 10 +
9 files changed, 497 insertions(+), 16 deletions(-)
create mode 100644 launcher/src/browser/horizon/pack.rs
diff --git a/docs/mod-browser.md b/docs/mod-browser.md
index 6c961fd42..a803420c3 100644
--- a/docs/mod-browser.md
+++ b/docs/mod-browser.md
@@ -159,12 +159,19 @@ into place only after `horizon_mods::index::check_file` passes (size, SHA-256, t
has a key, the file's own manifest against the index). A mod becomes `horizon-mods/.hmod`, turned on;
`mods disable` and `mods enable` switch it in `horizon-mods.txt`. When the index takes a file down, the launcher turns
it off the next time it reads the index or starts the game, says why, and refuses to install it or turn it back on.
-Horizon modpacks (`.hpack`) and shader packs are listed by the index but not installed by this launcher yet.
+A Horizon modpack (`.hpack`) installs as its own profile (`browser/horizon/pack.rs`): `horizon-packs//` holds the
+checked pack, `pack.json` and `home/`, the profile's game folder, where each of the pack's mods is downloaded and checked
+like any registry mod and turned on or off as the pack says; its overrides (settings, resource packs, a mod's saved
+settings) are copied in on the first install only, so the player's changes survive updates. A pack whose mod was taken
+down installs nothing. It is listed on the Modpacks tab with **Play** and **Remove**, and plays like an imported pack
+(`modpacks::apply_profile`). Shader packs are listed by the index but not installed by this launcher yet.
```sh
horizon-launcher mods search --source horizon --kind mod coords # with whether it is signed and what it may do
horizon-launcher mods install --source horizon coords_hud
horizon-launcher mods disable coords_hud
+horizon-launcher mods install --source horizon cozy # a modpack: its own profile
+horizon-launcher modpack play cozy
```
diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs
index 410fdd01e..5333e481d 100644
--- a/launcher/src/browser/horizon.rs
+++ b/launcher/src/browser/horizon.rs
@@ -111,12 +111,13 @@ fn fetch_index() -> Result<(Index, String), String> {
}
/// The browser's kind for a registry kind; None for one the launcher doesn't install yet
-/// (Horizon modpacks and shader packs, kinds newer than this launcher).
+/// (shader packs, kinds newer than this launcher).
fn kind_of(kind: &index::Kind) -> Option {
match kind {
index::Kind::Mod => Some(Kind::Mod),
index::Kind::ResourcePack => Some(Kind::ResourcePack),
- index::Kind::Modpack | index::Kind::Shader | index::Kind::Other(_) => None,
+ index::Kind::Modpack => Some(Kind::Modpack),
+ index::Kind::Shader | index::Kind::Other(_) => None,
}
}
@@ -259,6 +260,23 @@ impl Source for Registry {
body.push_str(&format!("- May {}\n", c.describe()));
}
}
+ if let Some(v) = newest.filter(|v| !v.requires.is_empty()) {
+ body.push_str(
+ "\n\n## Its mods\n\nInstalled with it into its own profile, each checked:\n\n",
+ );
+ for r in &v.requires {
+ let found = index
+ .project(&r.id)
+ .and_then(|m| Some((m, m.versions.iter().find(|w| w.version == r.version)?)));
+ let Some((m, w)) = found else { continue };
+ let may: Vec<&str> = w.capabilities.iter().map(|c| c.describe()).collect();
+ let may = match may.is_empty() {
+ true => String::new(),
+ false => format!(": may {}", may.join(", ")),
+ };
+ body.push_str(&format!("- {} {}{may}\n", m.name, w.version));
+ }
+ }
Ok(Details {
body,
links: vec![
@@ -325,9 +343,7 @@ fn relative(kind: Kind, id: &str, file_name: &str) -> Result {
match kind {
Kind::Mod => Ok(format!("{}/{id}.hmod", java::MODS_DIR)),
Kind::ResourcePack => Ok(format!("resourcepacks/{file_name}")),
- Kind::Modpack => {
- Err("Modpacks from Horizon's registry install from the Modpacks page.".into())
- }
+ Kind::Modpack => Err("A modpack installs as its own profile (pack::install).".into()),
}
}
@@ -352,17 +368,37 @@ fn install_from(
let p = index
.project(&project.id)
.ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?;
- let v = p
- .versions
+ let v = newest(index, p)?;
+ install_version(index, local, p, v, home, progress).map(|e| vec![e])
+}
+
+/// A project's newest version for this game that wasn't taken down.
+fn newest<'a>(index: &Index, p: &'a index::Project) -> Result<&'a index::Version, String> {
+ p.versions
.iter()
.find(|v| v.game == GAME && index.revoked(&p.id, &v.file.sha256).is_none())
- .ok_or_else(|| format!("{} has no version for {GAME} to install.", project.title))?;
+ .ok_or_else(|| format!("{} has no version for {GAME} to install.", p.name))
+}
+
+/// Installs version `v` of the registry's mod or resource pack `p` into the game folder `home`.
+fn install_version(
+ index: &Index,
+ local: bool,
+ p: &index::Project,
+ v: &index::Version,
+ home: &Path,
+ progress: &dyn Fn(&str, f32),
+) -> Result {
+ let project = project_of(p).ok_or_else(|| format!("{} can't be installed here.", p.name))?;
+ if let Some(r) = index.revoked(&p.id, &v.file.sha256) {
+ return Err(format!("{} was taken down: {}", p.name, r.reason));
+ }
let relative = relative(project.kind, &p.id, &v.file.name)?;
let mut list = installed::Installed::load(home);
let ours = |e: &installed::Entry| e.source == SourceId::Horizon && e.project == p.id;
let old = list.entries.iter().find(|e| ours(e)).cloned();
if old.as_ref().is_some_and(|o| o.version == v.version) {
- return Ok(vec![old.expect("checked")]);
+ return Ok(old.expect("checked"));
}
let target = home.join(&relative);
let taken_by = list.entries.iter().find(|e| !ours(e) && e.file == relative);
@@ -416,7 +452,7 @@ fn install_from(
list.entries.retain(|e| !ours(e));
list.entries.push(entry.clone());
list.save(home)?;
- Ok(vec![entry])
+ Ok(entry)
}
/// The mod id of an installed mod (`horizon-mods/` or `horizon-mods/.hmod`).
@@ -465,8 +501,12 @@ pub fn before_play(home: &Path) {
if !from_registry {
return;
}
- let kept = fs::read_to_string(home.join(CACHE)).ok();
- if let Some(index) = kept.and_then(|t| Index::parse(&t).ok()) {
+ let kept = fs::read_to_string(crate::backend::game_home().join(CACHE)).ok();
+ let parse = |t: String| match local() {
+ true => Index::parse_local(&t).ok(),
+ false => Index::parse(&t).ok(),
+ };
+ if let Some(index) = kept.and_then(parse) {
for line in turn_off_revoked(&index, home) {
eprintln!("{line}");
}
@@ -479,5 +519,6 @@ pub fn before_play(home: &Path) {
});
}
+pub mod pack;
#[cfg(test)]
mod tests;
diff --git a/launcher/src/browser/horizon/pack.rs b/launcher/src/browser/horizon/pack.rs
new file mode 100644
index 000000000..73dcd0cc1
--- /dev/null
+++ b/launcher/src/browser/horizon/pack.rs
@@ -0,0 +1,294 @@
+//! Horizon modpacks from the registry (`.hpack`, docs/api/mod-index.md), each played as its own
+//! profile: `horizon-packs//` in the game's home holds the pack's file, `pack.json` (what
+//! was installed) and `home/`, the profile's game folder: its saves, its options, and the pack's
+//! mods in `home/horizon-mods/`, each downloaded and checked against the index like any
+//! registry mod, turned on or off as the pack says. The pack's overrides (settings, resource
+//! packs, a mod's saved settings) are copied in once, when it is installed.
+use super::{fetch, index, install_version, local, newest, Index};
+use crate::browser::{java, FileRef};
+use horizon_mods::{index as idx, modpack::Modpack};
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+const RECORD: &str = "pack.json";
+
+/// Where registry modpacks live.
+pub fn packs_dir() -> PathBuf {
+ crate::backend::game_home().join("horizon-packs")
+}
+
+/// What `pack.json` keeps of an installed pack.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Installed {
+ pub id: String,
+ pub name: String,
+ pub version: String,
+ pub sha256: String,
+ /// The pack's mods: `id version`.
+ pub mods: Vec,
+ #[serde(skip)]
+ pub work: PathBuf,
+}
+
+/// The installed registry packs, by name.
+pub fn list() -> Vec {
+ list_in(&packs_dir())
+}
+
+fn list_in(dir: &Path) -> Vec {
+ let mut packs: Vec = fs::read_dir(dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .filter_map(|e| read(&e.path()))
+ .collect();
+ packs.sort_by_key(|p| p.name.to_lowercase());
+ packs
+}
+
+fn read(work: &Path) -> Option {
+ let text = fs::read_to_string(work.join(RECORD)).ok()?;
+ let mut pack: Installed = serde_json::from_str(&text).ok()?;
+ pack.work = work.to_path_buf();
+ Some(pack)
+}
+
+/// Whether `work` is a registry pack's folder.
+pub fn is_pack(work: &Path) -> bool {
+ work.join(RECORD).is_file()
+}
+
+/// The profile's game folder.
+pub fn home(work: &Path) -> PathBuf {
+ work.join("home")
+}
+
+/// Installs the registry modpack `id`: its newest version for this game, then each of its mods.
+/// Installing it again updates it; its saves and options stay.
+pub fn install(id: &str, progress: &dyn Fn(&str, f32)) -> Result {
+ install_in(&*index()?, local(), id, &packs_dir(), progress)
+}
+
+fn install_in(
+ index: &Index,
+ local: bool,
+ id: &str,
+ dir: &Path,
+ progress: &dyn Fn(&str, f32),
+) -> Result {
+ let p = index
+ .project(id)
+ .ok_or_else(|| format!("{id} isn't in Horizon's registry."))?;
+ if p.kind != idx::Kind::Modpack {
+ return Err(format!("{} is a {}, not a modpack.", p.name, p.kind.name()));
+ }
+ let v = newest(index, p)?;
+ let work = dir.join(&p.id);
+ let fresh = !work.exists();
+ let result = install_version_in(index, local, p, v, &work, progress);
+ if result.is_err() && fresh {
+ let _ = fs::remove_dir_all(&work);
+ }
+ result
+}
+
+fn install_version_in(
+ index: &Index,
+ local: bool,
+ p: &idx::Project,
+ v: &idx::Version,
+ work: &Path,
+ progress: &dyn Fn(&str, f32),
+) -> Result {
+ let line = format!("{} {}", p.name, v.version);
+ let file = FileRef {
+ url: v.file.url.clone(),
+ name: v.file.name.clone(),
+ size: v.file.size,
+ sha512: None,
+ sha256: Some(v.file.sha256.clone()),
+ sha1: None,
+ primary: true,
+ };
+ let path = fetch(&file, &work.join("downloads"), local, &|f| {
+ progress(&line, f)
+ })?;
+ idx::check_file(index, p, v, &path).inspect_err(|_| {
+ let _ = fs::remove_file(&path);
+ })?;
+ let pack = Modpack::read(&path)?;
+ let home = home(work);
+ fs::create_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?;
+ let mut mods = Vec::new();
+ for m in &pack.manifest.mods {
+ let found = index
+ .project(&m.id)
+ .and_then(|mp| Some((mp, mp.versions.iter().find(|w| w.version == m.version)?)));
+ let Some((mp, mv)) = found.filter(|(_, mv)| mv.file.sha256 == m.sha256) else {
+ return Err(format!(
+ "{} needs {} {}, which isn't in the registry.",
+ p.name, m.id, m.version
+ ));
+ };
+ install_version(index, local, mp, mv, &home, progress)?;
+ java::set_enabled(&home, &m.id, m.on)?;
+ mods.push(format!("{} {}", m.id, m.version));
+ }
+ // Settings once: the player's own changes to the profile stay on updates.
+ let first = !work.join(RECORD).exists();
+ if first {
+ Modpack::extract_overrides(&path, &home)?;
+ }
+ let kept = work.join(&v.file.name);
+ fs::rename(&path, &kept).map_err(|e| format!("{}: {e}", kept.display()))?;
+ let record = Installed {
+ id: p.id.clone(),
+ name: p.name.clone(),
+ version: v.version.clone(),
+ sha256: v.file.sha256.clone(),
+ mods,
+ work: work.to_path_buf(),
+ };
+ let text = serde_json::to_string_pretty(&record).map_err(|e| e.to_string())?;
+ fs::write(work.join(RECORD), text).map_err(|e| e.to_string())?;
+ Ok(record)
+}
+
+/// Turns the game's command into the pack's profile: its own game folder (the player's
+/// options.txt copied in when the pack brings none), its taken-down mods turned off first.
+pub fn apply(cmd: &mut Command, work: &Path) -> Result<(), String> {
+ if !is_pack(work) {
+ return Err(format!("{} is not an installed modpack.", work.display()));
+ }
+ let home = home(work);
+ fs::create_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?;
+ let options = home.join("options.txt");
+ let own = crate::backend::game_home().join("options.txt");
+ if !options.exists() && own.is_file() {
+ let _ = fs::copy(own, &options);
+ }
+ super::before_play(&home);
+ cmd.current_dir(&home).env("HORIZON_HOME", &home);
+ Ok(())
+}
+
+/// Removes an installed pack: its mods and the profile's saves.
+pub fn remove(work: &Path) -> Result<(), String> {
+ if work.parent() != Some(packs_dir().as_path()) || !is_pack(work) {
+ return Err(format!("{} is not an installed modpack.", work.display()));
+ }
+ fs::remove_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+
+ /// A local registry: the mod and a pack of it, as `file://` files.
+ fn registry(dir: &Path, on: bool, extra: &str) -> Index {
+ let hmod_src = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../crates/horizon-mods/tests/index/coords_hud-0.1.0.hmod");
+ let hmod = dir.join("coords_hud-0.1.0.hmod");
+ fs::copy(hmod_src, &hmod).unwrap();
+ let hmod_sha = idx::sha256_file(&hmod).unwrap();
+ let hpack = dir.join("cozy-1.0.0.hpack");
+ let mut zip = zip::ZipWriter::new(fs::File::create(&hpack).unwrap());
+ let o = zip::write::SimpleFileOptions::default();
+ zip.start_file("horizon-modpack.toml", o).unwrap();
+ write!(
+ zip,
+ "format = 1\nid = \"cozy\"\nname = \"Cozy\"\nversion = \"1.0.0\"\ngame = \"26.3\"\n\
+ [[mods]]\nid = \"coords_hud\"\nversion = \"0.1.0\"\nsha256 = \"{hmod_sha}\"\non = {on}\n"
+ )
+ .unwrap();
+ zip.start_file("overrides/options.txt", o).unwrap();
+ zip.write_all(b"renderDistance:8\n").unwrap();
+ zip.finish().unwrap();
+ let size = |p: &Path| fs::metadata(p).unwrap().len();
+ let text = format!(
+ r#"{{"schema": 1, "projects": [
+ {{"id": "coords_hud", "kind": "mod", "name": "Coordinates HUD", "summary": "", "license": "MIT",
+ "source": "https://x.test", "versions": [{{"version": "0.1.0", "api": "0.1", "side": "client",
+ "capabilities": ["game-read", "hud", "chat"], "game": "26.3", "file": {{"name": "coords_hud-0.1.0.hmod",
+ "url": "file://{}", "size": {}, "sha256": "{hmod_sha}"}}}}]}},
+ {{"id": "cozy", "kind": "modpack", "name": "Cozy", "summary": "", "license": "MIT",
+ "source": "https://x.test", "versions": [{{"version": "1.0.0", "api": "1", "game": "26.3",
+ "requires": [{{"id": "coords_hud", "version": "0.1.0", "sha256": "{hmod_sha}"}}],
+ "file": {{"name": "cozy-1.0.0.hpack", "url": "file://{}", "size": {}, "sha256": "{}"}}}}]}}
+ ]{extra}}}"#,
+ hmod.display(),
+ size(&hmod),
+ hpack.display(),
+ size(&hpack),
+ idx::sha256_file(&hpack).unwrap()
+ );
+ Index::parse_local(&text).unwrap()
+ }
+
+ fn scratch(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "horizon-launcher-hpack-{name}-{}",
+ std::process::id()
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn a_pack_installs_as_a_profile_with_its_mods() {
+ let dir = scratch("install");
+ let index = registry(&dir, false, "");
+ let packs = dir.join("horizon-packs");
+ let pack = install_in(&index, true, "cozy", &packs, &|_, _| {}).unwrap();
+ assert_eq!(pack.mods, ["coords_hud 0.1.0"]);
+ let home = home(&packs.join("cozy"));
+ assert!(home.join("horizon-mods/coords_hud.hmod").is_file());
+ assert!(
+ !java::is_enabled(&home, "coords_hud"),
+ "the pack turns it off"
+ );
+ assert_eq!(
+ fs::read_to_string(home.join("options.txt")).unwrap(),
+ "renderDistance:8\n"
+ );
+ assert_eq!(
+ list_in(&packs),
+ [Installed {
+ work: packs.join("cozy"),
+ ..pack
+ }]
+ );
+ // Settings the player changed stay on an update.
+ fs::write(home.join("options.txt"), "renderDistance:12\n").unwrap();
+ install_in(&index, true, "cozy", &packs, &|_, _| {}).unwrap();
+ assert_eq!(
+ fs::read_to_string(home.join("options.txt")).unwrap(),
+ "renderDistance:12\n"
+ );
+ // Not a modpack, and not there.
+ assert!(install_in(&index, true, "coords_hud", &packs, &|_, _| {})
+ .unwrap_err()
+ .contains("not a modpack"));
+ assert!(install_in(&index, true, "nope", &packs, &|_, _| {}).is_err());
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_pack_with_a_taken_down_mod_installs_nothing() {
+ let dir = scratch("revoked");
+ let index = registry(
+ &dir,
+ true,
+ r#", "revoked": [{"id": "coords_hud", "reason": "Test."}]"#,
+ );
+ let packs = dir.join("horizon-packs");
+ let e = install_in(&index, true, "cozy", &packs, &|_, _| {}).unwrap_err();
+ assert!(e.contains("taken down: Test."), "{e}");
+ assert!(!packs.join("cozy").exists(), "nothing left behind");
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/launcher/src/browser/horizon/tests.rs b/launcher/src/browser/horizon/tests.rs
index b46d7061d..caff9cd99 100644
--- a/launcher/src/browser/horizon/tests.rs
+++ b/launcher/src/browser/horizon/tests.rs
@@ -45,8 +45,8 @@ fn searches_by_kind_and_words() {
assert_eq!(found("", Kind::Mod), ["coords_hud"]);
assert_eq!(found("coordinates HUD", Kind::Mod), ["coords_hud"]);
assert!(found("zoom", Kind::Mod).is_empty());
- // Kinds this launcher can't install yet (modpacks, a world) are never offered.
- assert!(found("", Kind::Modpack).is_empty());
+ // Modpacks under Modpacks; a kind this launcher can't install yet (a world) never.
+ assert_eq!(found("", Kind::Modpack), ["cozy"]);
assert!(found("skyblock", Kind::ResourcePack).is_empty());
let p = hud(&index);
assert_eq!(p.support(), super::super::Support::Works);
diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs
index 4dd5d2d20..25bbe0bee 100644
--- a/launcher/src/cli.rs
+++ b/launcher/src/cli.rs
@@ -1214,6 +1214,23 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
} => {
let source = source.get()?;
let p = source.project(&project)?;
+ if p.kind == Kind::Modpack && p.source == SourceId::Horizon {
+ let pack = horizon::pack::install(&p.id, &line)?;
+ if as_json {
+ json(
+ serde_json::json!({"pack": pack.id, "version": pack.version, "mods": pack.mods, "home": horizon::pack::home(&pack.work)}),
+ );
+ } else {
+ println!(
+ "{} {} is installed as its own profile, with {}.",
+ pack.name,
+ pack.version,
+ pack.mods.join(", ")
+ );
+ println!("Play it: horizon-launcher modpack play {}", pack.id);
+ }
+ return Ok(());
+ }
if p.kind == Kind::Modpack {
let folder = modpacks::ports_dir().join("downloads");
let file =
@@ -1306,10 +1323,15 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
}
fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> {
+ use horizon_launcher::browser::horizon;
use horizon_launcher::modpacks::{self, Imported};
use horizon_port_pack::report::Status;
let log = &|line: String| eprintln!("{line}");
let work = |pack: &str| {
+ let registry = horizon::pack::packs_dir().join(pack);
+ if horizon::pack::is_pack(®istry) {
+ return Ok(registry);
+ }
let work = modpacks::ports_dir().join(pack);
modpacks::load(&work).map(|_| work)
};
@@ -1343,10 +1365,26 @@ fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> {
match action {
ModpackCmd::List => {
let packs = modpacks::list();
- if packs.is_empty() && !as_json {
+ let registry = horizon::pack::list();
+ if packs.is_empty() && registry.is_empty() && !as_json {
println!("No modpack imported yet: horizon-launcher modpack import ");
}
packs.iter().for_each(show);
+ for p in ®istry {
+ if as_json {
+ json(
+ serde_json::json!({"pack": p.id, "name": p.name, "version": p.version, "source": "horizon", "mods": p.mods}),
+ );
+ } else {
+ println!(
+ "{} {} ({}, from Horizon's registry)\n {}",
+ p.name,
+ p.version,
+ p.id,
+ p.mods.join(", ")
+ );
+ }
+ }
}
ModpackCmd::Import { path } => show(&modpacks::import(&path, log)?),
ModpackCmd::Port {
diff --git a/launcher/src/main.rs b/launcher/src/main.rs
index 4a68ecdef..7aaeb8d9b 100644
--- a/launcher/src/main.rs
+++ b/launcher/src/main.rs
@@ -202,6 +202,8 @@ struct Launcher {
/// The Modpacks page: the imported packs (read when the page first opens), the one shown,
/// the report's filter, and the pipeline step running now with its log.
packs: Vec,
+ /// Modpacks installed from Horizon's registry, each its own profile.
+ registry_packs: Vec,
packs_loaded: Option,
pack_open: Option,
pack_filter: Option,
@@ -326,6 +328,7 @@ impl Launcher {
play_pressed: None,
bench: perf::Bench::from_env(),
packs: Vec::new(),
+ registry_packs: Vec::new(),
packs_loaded: None,
pack_open: None,
pack_filter: None,
diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs
index 909c6cfae..acd8241a5 100644
--- a/launcher/src/modpacks.rs
+++ b/launcher/src/modpacks.rs
@@ -7,6 +7,7 @@
//! `home/`, the profile's own saves and options. Nothing is uploaded or shared: mod jars are
//! often All Rights Reserved, so the ports stay on the player's machine.
use crate::backend;
+use crate::browser::horizon::pack as horizon_pack;
use horizon_port_pack::{
fetch::{Fetched, How},
import::Pack,
@@ -232,6 +233,9 @@ pub fn outcome(pack: &Imported) -> String {
/// Removes an imported pack: its jars, ports and the profile's saves.
pub fn remove(work: &Path) -> Result<(), String> {
+ if horizon_pack::is_pack(work) {
+ return horizon_pack::remove(work);
+ }
if work.parent() != Some(ports_dir().as_path()) {
return Err(format!("{} is not an imported pack", work.display()));
}
@@ -245,7 +249,11 @@ pub fn profile_home(work: &Path) -> PathBuf {
/// Turns the game's command into this pack's profile: its own home (the player's options.txt
/// copied in the first time, so keys and video settings carry over) and its carried-over mods.
+/// A modpack from Horizon's registry (`horizon-packs//`) plays its own profile the same way.
pub fn apply_profile(cmd: &mut Command, work: &Path) -> Result<(), String> {
+ if horizon_pack::is_pack(work) {
+ return horizon_pack::apply(cmd, work);
+ }
// Only mods that load together: the game would refuse the later of two sharing a namespace.
let (mods, _) = pipeline::loadable(&carried(work));
if mods.is_empty() {
diff --git a/launcher/src/modpacks_page.rs b/launcher/src/modpacks_page.rs
index 6346f8a0b..25df3966f 100644
--- a/launcher/src/modpacks_page.rs
+++ b/launcher/src/modpacks_page.rs
@@ -1,6 +1,7 @@
//! Imported modpacks, on the Mods page's Modpacks tab: import a pack, read its coverage report,
//! port what this computer can and play it as its own profile (`horizon_launcher::modpacks`).
use super::*;
+use horizon_launcher::browser::horizon::pack as horizon_pack;
use horizon_launcher::modpacks::{self, Imported};
use horizon_port_pack::report::Status;
use std::path::PathBuf;
@@ -130,6 +131,7 @@ impl Launcher {
if self.packs_loaded.is_none() {
self.mods.report_list.reset();
self.packs = modpacks::list();
+ self.registry_packs = horizon_pack::list();
if self.pack_open.is_none() {
self.pack_open = self.packs.first().map(|p| p.slug.clone());
}
@@ -177,6 +179,12 @@ impl Launcher {
if let Some(e) = &self.pack_error {
page = page.child(notice(e.clone(), &t));
}
+ if !self.registry_packs.is_empty() {
+ page = page.child(self.registry_pack_rows(cx));
+ }
+ if self.packs.is_empty() && !self.registry_packs.is_empty() {
+ return page;
+ }
if self.packs.is_empty() {
return page.child(
text(theme::CAPTION)
@@ -216,6 +224,78 @@ impl Launcher {
}
}
+ /// The modpacks installed from Horizon's registry: each plays its own profile.
+ fn registry_pack_rows(&self, cx: &mut Context) -> Div {
+ let t = self.theme;
+ let mut list = div().flex().flex_col();
+ for (i, p) in self.registry_packs.iter().enumerate() {
+ let (play, remove) = (p.work.clone(), p.work.clone());
+ let id = p.id.clone();
+ let key = format!("horizon:{id}");
+ let confirming = self.confirm_remove.as_deref() == Some(key.as_str());
+ let right = div()
+ .flex()
+ .gap(px(8.))
+ .child(
+ button(format!("play-pack-{id}"), "Play", Kind::Primary, &t).on_click(
+ cx.listener(move |this, _: &ClickEvent, _, cx| {
+ this.play_pack(play.clone());
+ cx.notify();
+ }),
+ ),
+ )
+ .child(
+ button(
+ format!("remove-pack-{id}"),
+ if confirming {
+ "Remove for good"
+ } else {
+ "Remove"
+ },
+ if confirming {
+ Kind::Secondary
+ } else {
+ Kind::Ghost
+ },
+ &t,
+ )
+ .when(confirming, |b| b.text_color(t.danger))
+ .on_click(cx.listener(
+ move |this, _: &ClickEvent, _, cx| {
+ if this.confirm_remove.as_ref() == Some(&key) {
+ match horizon_pack::remove(&remove) {
+ Ok(()) => this.packs_loaded = None,
+ Err(e) => this.pack_error = Some(e),
+ }
+ this.confirm_remove = None;
+ } else {
+ this.confirm_remove = Some(key.clone());
+ }
+ cx.notify();
+ },
+ )),
+ );
+ let detail = format!(
+ "{} from Horizon's registry, its own profile: {}",
+ p.version,
+ p.mods.join(", ")
+ );
+ list = list.child(index_row(
+ i + 1,
+ p.name.clone(),
+ Some(
+ text(theme::CAPTION)
+ .text_color(t.muted)
+ .child(detail)
+ .into_any_element(),
+ ),
+ Some(right.into_any_element()),
+ &t,
+ ));
+ }
+ list
+ }
+
fn pack_log_plate(&self, t: &Theme) -> Div {
let start = self.pack_log.len().saturating_sub(LOG_SHOWN);
plate(t)
diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs
index 5e60549a1..50434756c 100644
--- a/launcher/src/mods_page.rs
+++ b/launcher/src/mods_page.rs
@@ -468,6 +468,16 @@ impl Launcher {
None => source.project(&id)?,
};
modpack = p.kind == PackKind::Modpack;
+ if modpack && p.source == SourceId::Horizon {
+ let pack = horizon::pack::install(&p.id, &progress)?;
+ return Ok(format!(
+ "Installed {} {} as its own profile with {}, each checked. Play it \
+ from the list above.",
+ pack.name,
+ pack.version,
+ pack.mods.join(", ")
+ ));
+ }
if modpack {
let folder = modpacks::ports_dir().join("downloads");
let file = installed::fetch_modpack(&*source, &p, &folder, &|f| {
From 348675c5387a11a8992a99428b7609bd78047c58 Mon Sep 17 00:00:00 2001
From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Date: Sun, 25 Oct 2026 02:52:19 +0200
Subject: [PATCH 06/88] Packs: open streamed archives the way Java's ZipFile
does
A resource pack written while it streams (Nexo's server behind
resourcepack.gommehd.io, gommehd.net's required pack) leaves every local
header a stub, every uncompressed size at 0xFFFFFFFF and the END record's
entry counts and disk number at 0 and 0xFFFF. Java tolerates all three;
the zip crate's ZipArchive refuses the END record as multi-disk and empty,
so a required server pack failed its reload and the join never got through
(each retry also rebuilt the renderer, once a second).
Count the real central-directory entries and normalize the END record's
disk and count fields when they disagree with it, and bound the inflate
output when an entry's size is the 0xFFFFFFFF sentinel.
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
crates/horizon-client/src/zip.rs | 108 ++++++++++++++++++++++++++++++-
1 file changed, 106 insertions(+), 2 deletions(-)
diff --git a/crates/horizon-client/src/zip.rs b/crates/horizon-client/src/zip.rs
index 22cab132d..17442858e 100644
--- a/crates/horizon-client/src/zip.rs
+++ b/crates/horizon-client/src/zip.rs
@@ -23,7 +23,8 @@ impl Zip {
pub fn open(path: &Path) -> io::Result {
Self::from_bytes(fs::read(path)?)
}
- pub fn from_bytes(data: Vec) -> io::Result {
+ pub fn from_bytes(mut data: Vec) -> io::Result {
+ normalize_end(&mut data);
let archive = ZipArchive::new(Cursor::new(Arc::from(data))).map_err(invalid)?;
let entries = (0..archive.len())
.filter_map(|i| Some((archive.name_for_index(i)?.replace('\\', "/"), i)))
@@ -51,7 +52,14 @@ impl Zip {
match method {
CompressionMethod::Stored => Ok(raw),
CompressionMethod::Deflated => {
- miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, size.max(1) * 2 + 1024)
+ // Streamed archives write 0xFFFFFFFF for the uncompressed
+ // size; bound the output instead of trusting it.
+ let limit = if size == u32::MAX as usize {
+ 1 << 30
+ } else {
+ size.max(1) * 2 + 1024
+ };
+ miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, limit)
.map_err(|_| invalid("corrupt deflate stream"))
}
_ => Err(invalid("unsupported zip compression")),
@@ -59,6 +67,59 @@ impl Zip {
}
}
+/// The 22 fixed bytes of the end-of-central-directory record.
+const END_HEADER: usize = 22;
+
+/// Java's `ZipFile` ignores the END record's disk numbers and file counts,
+/// reading the central directory from `cenpos` to `cenpos + cenlen` whatever
+/// they say; the `zip` crate insists the record agrees with the directory.
+/// Packs written while streaming (Nexo serves them for gommehd.net, for one)
+/// leave every file's local header a stub, the uncompressed sizes at
+/// 0xFFFFFFFF and the END counts and disk number at 0 and 0xFFFF — archives
+/// Java opens but the crate refuses. Count the real directory entries and
+/// normalize the record so it does not look multi-disk or empty.
+fn normalize_end(data: &mut [u8]) {
+ if data.len() < END_HEADER {
+ return;
+ }
+ let u16_at = |data: &[u8], at: usize| u16::from_le_bytes(data[at..at + 2].try_into().unwrap());
+ let u32_at = |data: &[u8], at: usize| u32::from_le_bytes(data[at..at + 4].try_into().unwrap());
+ // The END record's comment can hide the signature: scan back through the
+ // last 64 KiB, like every zip reader.
+ let start = data.len().saturating_sub(END_HEADER + u16::MAX as usize);
+ let mut end = None;
+ for pos in (start..=data.len().saturating_sub(END_HEADER)).rev() {
+ if data[pos..pos + 4] == [0x50, 0x4b, 0x05, 0x06]
+ && pos + END_HEADER + u16_at(data, pos + 20) as usize <= data.len()
+ {
+ end = Some(pos);
+ break;
+ }
+ }
+ let Some(end) = end else { return };
+ // The directory's real position and length, as Java derives them; the
+ // recorded offset is relative to the archive's start.
+ let cenlen = u32_at(data, end + 12) as usize;
+ let cenpos = end.saturating_sub(cenlen);
+ let mut count = 0u16;
+ let mut p = cenpos;
+ while p + 46 <= end && data[p..p + 4] == [0x50, 0x4b, 0x01, 0x02] {
+ count = count.saturating_add(1);
+ p += 46
+ + u16_at(data, p + 28) as usize
+ + u16_at(data, p + 30) as usize
+ + u16_at(data, p + 32) as usize;
+ }
+ let disk = u16_at(data, end + 4);
+ let with_directory = u16_at(data, end + 6);
+ if disk == with_directory && u16_at(data, end + 8) == count && u16_at(data, end + 10) == count {
+ return;
+ }
+ data[end + 4..end + 10].fill(0);
+ data[end + 8..end + 10].copy_from_slice(&count.to_le_bytes());
+ data[end + 10..end + 12].copy_from_slice(&count.to_le_bytes());
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -207,4 +268,47 @@ mod tests {
cut.truncate(cut.len() / 2);
assert!(Zip::from_bytes(cut).is_err());
}
+
+ /// A pack as a streaming writer serves it (Nexo/gommehd.net): every
+ /// local header is a stub, the uncompressed sizes are 0xFFFFFFFF and the
+ /// END record's counts and disk numbers are wrong. Java's ZipFile opens
+ /// it anyway; so do we.
+ #[test]
+ fn reads_a_streamed_archive() {
+ let files: [(&str, &[u8], bool); 2] = [
+ ("pack.mcmeta", b"{\"pack\":{}}", true),
+ ("a/b.txt", b"streamed entry", true),
+ ];
+ let mut out = Vec::new();
+ let mut central = Vec::new();
+ for (name, body, _) in files {
+ let data = miniz_oxide::deflate::compress_to_vec(body, 6);
+ let offset = out.len() as u32;
+ out.extend(0x0403_4b50u32.to_le_bytes());
+ out.extend([0; 26]);
+ out.extend(&data);
+ central.extend(0x0201_4b50u32.to_le_bytes());
+ central.extend([20, 0, 20, 0, 0, 0]);
+ central.extend(8u16.to_le_bytes());
+ central.extend([0; 8]);
+ central.extend((data.len() as u32).to_le_bytes());
+ central.extend(u32::MAX.to_le_bytes());
+ central.extend((name.len() as u16).to_le_bytes());
+ central.extend([0; 12]);
+ central.extend(offset.to_le_bytes());
+ central.extend(name.as_bytes());
+ }
+ let start = out.len() as u32;
+ out.extend(¢ral);
+ out.extend(0x0605_4b50u32.to_le_bytes());
+ out.extend(u16::MAX.to_le_bytes());
+ out.extend([0; 6]);
+ out.extend((central.len() as u32).to_le_bytes());
+ out.extend(start.to_le_bytes());
+ out.extend([0; 2]);
+ let zip = Zip::from_bytes(out).unwrap();
+ assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]);
+ assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}");
+ assert_eq!(zip.read("a/b.txt").unwrap(), b"streamed entry");
+ }
}
From e7f85e5bfd55783f91348a7f9c6701d201e1cda3 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 10:44:31 +0100
Subject: [PATCH 07/88] Zip: test the streamed shapes Java 25's ZipFile opens
ZipFile refuses a 0xFFFFFFFF size without its Zip64 extra field ("invalid
zip64 extra len size"), so the test builds both shapes it accepts: real
sizes, and the sentinel with the extra (the zip crate reads the real size
from it). With every accepted shape carrying a real size, the inflate
limit needs no special case.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/zip.rs | 105 ++++++++++++++++---------------
1 file changed, 56 insertions(+), 49 deletions(-)
diff --git a/crates/horizon-client/src/zip.rs b/crates/horizon-client/src/zip.rs
index 17442858e..7f8c2a614 100644
--- a/crates/horizon-client/src/zip.rs
+++ b/crates/horizon-client/src/zip.rs
@@ -52,14 +52,7 @@ impl Zip {
match method {
CompressionMethod::Stored => Ok(raw),
CompressionMethod::Deflated => {
- // Streamed archives write 0xFFFFFFFF for the uncompressed
- // size; bound the output instead of trusting it.
- let limit = if size == u32::MAX as usize {
- 1 << 30
- } else {
- size.max(1) * 2 + 1024
- };
- miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, limit)
+ miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, size.max(1) * 2 + 1024)
.map_err(|_| invalid("corrupt deflate stream"))
}
_ => Err(invalid("unsupported zip compression")),
@@ -74,10 +67,10 @@ const END_HEADER: usize = 22;
/// reading the central directory from `cenpos` to `cenpos + cenlen` whatever
/// they say; the `zip` crate insists the record agrees with the directory.
/// Packs written while streaming (Nexo serves them for gommehd.net, for one)
-/// leave every file's local header a stub, the uncompressed sizes at
-/// 0xFFFFFFFF and the END counts and disk number at 0 and 0xFFFF — archives
-/// Java opens but the crate refuses. Count the real directory entries and
-/// normalize the record so it does not look multi-disk or empty.
+/// leave every file's local header a stub and the END counts and disk number
+/// at 0 and 0xFFFF: archives Java opens but the crate refuses. Count the real
+/// directory entries and normalize the record so it does not look multi-disk
+/// or empty.
fn normalize_end(data: &mut [u8]) {
if data.len() < END_HEADER {
return;
@@ -270,45 +263,59 @@ mod tests {
}
/// A pack as a streaming writer serves it (Nexo/gommehd.net): every
- /// local header is a stub, the uncompressed sizes are 0xFFFFFFFF and the
- /// END record's counts and disk numbers are wrong. Java's ZipFile opens
- /// it anyway; so do we.
+ /// local header is a 30-byte stub and the END record's disk number and
+ /// counts are wrong. Java 25's `ZipFile` opens it, with each size either
+ /// in the directory or as 0xFFFFFFFF plus its Zip64 extra field (without
+ /// that field it refuses the archive: "invalid zip64 extra len size").
#[test]
fn reads_a_streamed_archive() {
- let files: [(&str, &[u8], bool); 2] = [
- ("pack.mcmeta", b"{\"pack\":{}}", true),
- ("a/b.txt", b"streamed entry", true),
- ];
- let mut out = Vec::new();
- let mut central = Vec::new();
- for (name, body, _) in files {
- let data = miniz_oxide::deflate::compress_to_vec(body, 6);
- let offset = out.len() as u32;
- out.extend(0x0403_4b50u32.to_le_bytes());
- out.extend([0; 26]);
- out.extend(&data);
- central.extend(0x0201_4b50u32.to_le_bytes());
- central.extend([20, 0, 20, 0, 0, 0]);
- central.extend(8u16.to_le_bytes());
- central.extend([0; 8]);
- central.extend((data.len() as u32).to_le_bytes());
- central.extend(u32::MAX.to_le_bytes());
- central.extend((name.len() as u16).to_le_bytes());
- central.extend([0; 12]);
- central.extend(offset.to_le_bytes());
- central.extend(name.as_bytes());
+ for zip64 in [false, true] {
+ let files: [(&str, &[u8]); 2] = [
+ ("pack.mcmeta", b"{\"pack\":{}}"),
+ ("a/b.txt", b"streamed entry"),
+ ];
+ let mut out = Vec::new();
+ let mut central = Vec::new();
+ for (name, body) in files {
+ let data = miniz_oxide::deflate::compress_to_vec(body, 6);
+ let offset = out.len() as u32;
+ out.extend(0x0403_4b50u32.to_le_bytes());
+ out.extend([0; 26]);
+ out.extend(&data);
+ let extra: Vec = if zip64 {
+ [1u16, 8]
+ .iter()
+ .flat_map(|v| v.to_le_bytes())
+ .chain((body.len() as u64).to_le_bytes())
+ .collect()
+ } else {
+ Vec::new()
+ };
+ central.extend(0x0201_4b50u32.to_le_bytes());
+ central.extend([20, 0, 20, 0, 0, 0]);
+ central.extend(8u16.to_le_bytes());
+ central.extend([0; 8]);
+ central.extend((data.len() as u32).to_le_bytes());
+ central.extend(if zip64 { u32::MAX } else { body.len() as u32 }.to_le_bytes());
+ central.extend((name.len() as u16).to_le_bytes());
+ central.extend((extra.len() as u16).to_le_bytes());
+ central.extend([0; 10]);
+ central.extend(offset.to_le_bytes());
+ central.extend(name.as_bytes());
+ central.extend(extra);
+ }
+ let start = out.len() as u32;
+ out.extend(¢ral);
+ out.extend(0x0605_4b50u32.to_le_bytes());
+ out.extend(u16::MAX.to_le_bytes());
+ out.extend([0; 6]);
+ out.extend((central.len() as u32).to_le_bytes());
+ out.extend(start.to_le_bytes());
+ out.extend([0; 2]);
+ let zip = Zip::from_bytes(out).unwrap();
+ assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]);
+ assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}");
+ assert_eq!(zip.read("a/b.txt").unwrap(), b"streamed entry");
}
- let start = out.len() as u32;
- out.extend(¢ral);
- out.extend(0x0605_4b50u32.to_le_bytes());
- out.extend(u16::MAX.to_le_bytes());
- out.extend([0; 6]);
- out.extend((central.len() as u32).to_le_bytes());
- out.extend(start.to_le_bytes());
- out.extend([0; 2]);
- let zip = Zip::from_bytes(out).unwrap();
- assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]);
- assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}");
- assert_eq!(zip.read("a/b.txt").unwrap(), b"streamed entry");
}
}
From 57ee0810381b2d1d271fcfa6678bb8de456c7151 Mon Sep 17 00:00:00 2001
From: levzzz <86072227+levzzz5154@users.noreply.github.com>
Date: Sun, 25 Oct 2026 15:56:53 +0500
Subject: [PATCH 08/88] Keep sprint state independent of held sprint keys
Let PlayerCommand control the server sprint flag, matching vanilla, so releasing Ctrl cannot leave the client's speed modifier and FOV stuck. Cover the packet sequence and FOV recovery in regression tests.
Co-Authored-By: Codex (GPT-6)
---
crates/horizon-client/src/game/agent.rs | 3 +-
crates/horizon-client/src/lan/hub.rs | 4 +-
crates/horizon-client/tests/lan_bot.rs | 59 +++++++++++++++++++++++++
tools/lan_e2e.py | 46 +++++++++++++++++++
4 files changed, 110 insertions(+), 2 deletions(-)
diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs
index f6b68aa74..57c12da97 100644
--- a/crates/horizon-client/src/game/agent.rs
+++ b/crates/horizon-client/src/game/agent.rs
@@ -469,7 +469,8 @@ impl Game<'_> {
"flying": p.flying,
"fall_flying": p.fall_flying,
"sneaking": self.keys.contains(&KeyCode::ShiftLeft),
- "sprinting": self.keys.contains(&KeyCode::ControlLeft),
+ "sprinting": p.sprinting,
+ "fov_modifier": self.view.fov_modifier,
"health": p.health.health(),
"absorption": p.health.absorption(),
// The hurt animation's ticks left (the camera's hurt tilt).
diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs
index c2a395899..dd0a32f22 100644
--- a/crates/horizon-client/src/lan/hub.rs
+++ b/crates/horizon-client/src/lan/hub.rs
@@ -1984,7 +1984,9 @@ impl Hub {
S::PlayerInput(p) => {
self.guests[i].input = p.flags;
self.guests[i].sneaking = p.flags & 32 != 0;
- self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0;
+ // handlePlayerInput only records keys and updates crouching.
+ // Sprinting persists after the sprint key is released (or
+ // starts with a double tap); PlayerCommand changes it.
}
// OPEN_INVENTORY (the ridden mount's inventory) and
// START_FALL_FLYING (checked against the guest's chest slot
diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs
index 6dd1b8258..34e8265a1 100644
--- a/crates/horizon-client/tests/lan_bot.rs
+++ b/crates/horizon-client/tests/lan_bot.rs
@@ -278,6 +278,65 @@ fn run(
handle.join().unwrap().unwrap()
}
+#[test]
+fn sprint_commands_survive_keyboard_input_changes() {
+ let Some(resources) = resources() else {
+ return;
+ };
+ let mut s = server(&resources);
+ let port = s.hub.lan.port;
+ let _bot = run(&mut s, move || connect(port, "Sprinter", true));
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while s.hub.guests.is_empty() {
+ s.tick(&[]);
+ assert!(Instant::now() < deadline, "guest did not join");
+ thread::yield_now();
+ }
+ let id = s.hub.guests[0].entity_id;
+ s.hub.guests[0].loaded = true;
+ s.hub.guests[0]
+ .inbox
+ .push_back(S::PlayerCommand(play::PlayerCommand {
+ id,
+ action: 1,
+ data: 0,
+ }));
+ s.tick(&[]);
+ assert!(s.hub.guests[0].sprinting);
+ // LocalPlayer keeps sprinting after Ctrl is released while W remains
+ // down. Double-tap sprint also sends forward without the sprint key.
+ for flags in [65, 1, 0, 33] {
+ s.hub.guests[0]
+ .inbox
+ .push_back(S::PlayerInput(play::PlayerInput { flags }));
+ s.tick(&[]);
+ let g = &s.hub.guests[0];
+ assert!(
+ g.sprinting,
+ "keyboard input {flags} cleared the sprint flag"
+ );
+ assert_eq!(g.input, flags);
+ assert_eq!(g.sneaking, flags & 32 != 0);
+ }
+ s.hub.guests[0]
+ .inbox
+ .push_back(S::PlayerCommand(play::PlayerCommand {
+ id,
+ action: 2,
+ data: 0,
+ }));
+ s.tick(&[]);
+ assert!(!s.hub.guests[0].sprinting);
+ s.hub.guests[0]
+ .inbox
+ .push_back(S::PlayerInput(play::PlayerInput { flags: 65 }));
+ s.tick(&[]);
+ assert!(
+ !s.hub.guests[0].sprinting,
+ "keyboard input started a sprint"
+ );
+}
+
#[test]
fn status_and_join() {
let Some(resources) = resources() else {
diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py
index 0c8979f0a..892e393f0 100755
--- a/tools/lan_e2e.py
+++ b/tools/lan_e2e.py
@@ -6162,5 +6162,51 @@ CHECKS += ['falling']
CHECK_FNS.update(falling=check_falling)
+def check_sprint_fov(host, guest, out):
+ """Releasing Ctrl must preserve a sprint until W is released, then reset FOV.
+
+ PlayerInput reports keys; PlayerCommand starts/stops the sprint. Confusing
+ them clears the client's sprint flag while leaving its speed modifier on.
+ """
+ seen = {}
+ for game in (host, guest):
+ game('command', command='gamemode creative')
+ game('command', command='effect clear @s')
+ game.raw('options-set', 'fovEffectScale', '1.0')
+ x, y, z = map(math.floor, pos_of(game))
+ game('command', command=f'fill {x - 2} {y} {z - 2} {x + 2} {y + 3} {z + 20} minecraft:air')
+ game('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 2} {y - 1} {z + 20} minecraft:stone')
+ game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0')
+ game.wait(20)
+ try:
+ game.raw('key', 'w', 'down')
+ game.raw('key', 'ctrl', 'down')
+ game.wait(10)
+ started = game('state')['player']
+ game.raw('key', 'ctrl', 'up')
+ game.wait(10)
+ released_ctrl = game('state')['player']
+ game.raw('key', 'w', 'up')
+ game.wait(20)
+ stopped = game('state')['player']
+ finally:
+ game.raw('key', 'ctrl', 'up')
+ game.raw('key', 'w', 'up')
+ seen[game.name] = states = {
+ label: {k: p[k] for k in ('sprinting', 'fov_modifier')}
+ for label, p in [('started', started), ('released_ctrl', released_ctrl), ('stopped', stopped)]
+ }
+ for label in ('started', 'released_ctrl'):
+ assert states[label]['sprinting'], f'{game.name} {label}: {states}'
+ assert abs(states[label]['fov_modifier'] - 1.15) < 0.002, f'{game.name} {label}: {states}'
+ assert not stopped['sprinting'], f'{game.name}: {states}'
+ assert abs(stopped['fov_modifier'] - 1.0) < 0.002, f'{game.name}: {states}'
+ return seen
+
+
+CHECKS += ['sprint-fov']
+CHECK_FNS['sprint-fov'] = check_sprint_fov
+
+
if __name__ == '__main__':
main()
From 1ec6d6d734ff97716ed5f6e1796a13db366006bd Mon Sep 17 00:00:00 2001
From: levzzz <86072227+levzzz5154@users.noreply.github.com>
Date: Sun, 25 Oct 2026 16:15:35 +0500
Subject: [PATCH 09/88] Detach entity passengers when their vehicle is removed
Clear remote passenger mount and pose flags when a vehicle disappears, matching Entity.setRemoved. Add a two-passenger boat destruction check for both single-player paths and LAN observers.
Co-Authored-By: Codex (GPT-6)
---
crates/horizon-client/src/game/creatures.rs | 6 ++-
crates/horizon-client/src/game/remote.rs | 8 ++--
tools/lan_e2e.py | 50 +++++++++++++++++++++
3 files changed, 58 insertions(+), 6 deletions(-)
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index 0bb7bbe85..5cfcefdb8 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -321,7 +321,7 @@ impl Game<'_> {
.iter()
.filter(|m| m.distance_sqr(center) <= radius * radius)
.map(|m| {
- serde_json::json!({
+ let mut state = serde_json::json!({
"id": m.id,
"kind": m.kind.id,
"pos": [m.position.x, m.position.y, m.position.z],
@@ -370,7 +370,9 @@ impl Game<'_> {
"patrol_target": s.patrol_target,
"vehicle": m.extra.mount,
})),
- })
+ });
+ state["passenger"] = serde_json::json!(m.extra.passenger);
+ state
})
.collect();
serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() })
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 5a71b13a8..efaf02b95 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -1515,10 +1515,10 @@ impl Game<'_> {
self.turn_remote_projectile(id, rotation);
}
fn remove_entity(&mut self, id: i32) {
- // The vehicle the player rode is gone (Entity.removeVehicle).
- if self.riding == Some(id as u32) {
- self.riding = None;
- }
+ // Entity.setRemoved detaches every passenger, even when no empty
+ // SetPassengers packet preceded the vehicle's removal. Otherwise
+ // mobs and other players keep their passenger pose after it is gone.
+ self.remote_set_passengers(id, &[]);
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py
index 0c8979f0a..e146364b2 100755
--- a/tools/lan_e2e.py
+++ b/tools/lan_e2e.py
@@ -6162,5 +6162,55 @@ CHECKS += ['falling']
CHECK_FNS.update(falling=check_falling)
+def check_boat_dismount_pose(host, guest, out):
+ """Removing a boat detaches its mobs on the server and every observing client."""
+ x, y, z = map(math.floor, pos_of(host))
+ bx, bz = x + 3.5, z + 3.5
+ tag = 'boat_dismount_pose'
+ host('command', command='gamemode creative')
+ host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 8} {y - 1} {z + 8} minecraft:stone')
+ host('command', command=f'fill {x - 2} {y} {z - 2} {x + 8} {y + 4} {z + 8} minecraft:air')
+ host('command', command=f'summon minecraft:oak_boat {bx} {y} {bz} {{Tags:["{tag}"]}}')
+ for _ in range(2):
+ host('command', command=f'summon minecraft:husk {bx} {y} {bz} {{NoAI:1b,Tags:["{tag}"]}}')
+ host.wait(5)
+ try:
+ host.wait(20)
+ boat = next(o for o in host('status')['objects']
+ if o['kind'].endswith('oak_boat') and math.dist(o['position'], [bx, y, bz]) < 2)
+ riders = [m['id'] for m in host.raw('mobs', 64)['near']
+ if m['kind'] == 'minecraft:husk' and m['mount'] == boat['id']]
+ assert len(riders) == 2, f'the boat did not collect both husks: {riders}'
+ for game in (host, guest):
+ game.wait(10)
+ for rider in riders:
+ m = mob_seen(game, rider)
+ assert m and m['mount'] == boat['id'] and m['passenger'], f'{game.name} did not see seated husk {rider}: {m}'
+ game.raw('look-at', bx, y + 1, bz)
+ game.shot(out, 'boat-passengers-seated')
+ host('command', command=f'tp @s {bx - 3} {y} {bz} 0 0')
+ host.wait(5)
+ # Aim at the near rim, below the riders, so their boxes cannot
+ # intercept the creative player's one hit that destroys the boat.
+ host.raw('look-at', bx - 0.55, y + 0.1, bz)
+ host.raw('mouse', 'left', 'click')
+ seen = {}
+ for game in (host, guest):
+ game.wait(20)
+ assert all(o['id'] != boat['id'] for o in game('status')['objects']), f'{game.name} still sees the boat'
+ seen[game.name] = [mob_seen(game, rider) for rider in riders]
+ game.raw('look-at', bx, y + 1, bz)
+ game.shot(out, 'boat-passengers-dismounted')
+ for m in seen[game.name]:
+ assert m and m['mount'] is None and not m['passenger'], f'{game.name} still draws a removed boat\'s passenger: {m}'
+ return {name: [{k: m[k] for k in ('id', 'mount', 'passenger')} for m in mobs] for name, mobs in seen.items()}
+ finally:
+ host('command', command=f'kill @e[tag={tag}]')
+
+
+CHECKS += ['boat-dismount-pose']
+CHECK_FNS['boat-dismount-pose'] = check_boat_dismount_pose
+
+
if __name__ == '__main__':
main()
From 4032e162ce1cb2c3552edda9a744d910383db287 Mon Sep 17 00:00:00 2001
From: socksprox
Date: Sun, 25 Oct 2026 02:06:53 +0200
Subject: [PATCH 10/88] Draw translucent particles after translucent terrain
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Quad particles all went into the entity batch, drawn before translucent
terrain with depth writes on: a stained-glass crumb wrote its depth and
the sorted translucent pass then culled the glass behind it, so breaking
glass in front of glass cut holes through the wall.
Vanilla 26.3 submits quad particles to two phases: opaque layers draw
with the solids and translucent layers draw in an "afterTerrain" phase
right after the translucent section pass (the translucent particle
pipeline still writes depth, so ordering is what matters). Mirror that:
HudAtlas records which sprites have a 0 < alpha < 255 texel
(`SpriteContents.transparency().hasTranslucent`), particles classify
their layer the way `SingleQuadParticle.getLayer` does — the type's
hardcoded layer, or `Layer.bySprite` for terrain, item and block marker
sprites — and the entity batch routes those quads to a sixth bucket the
renderer draws immediately after translucent terrain.
Fixes #1679.
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
.../examples/probe/marker_particles_probe.rs | 2 +-
.../probe/particle_providers_probe.rs | 2 +-
crates/horizon-client/src/game.rs | 6 +-
crates/horizon-client/src/gfx.rs | 43 +++++++++++---
crates/horizon-client/src/gfx/entity_batch.rs | 15 +++--
crates/horizon-client/src/hud.rs | 15 ++++-
crates/horizon-client/src/particles.rs | 58 +++++++++++++++++--
7 files changed, 118 insertions(+), 23 deletions(-)
diff --git a/crates/horizon-client/examples/probe/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs
index 190751d79..6b05af356 100644
--- a/crates/horizon-client/examples/probe/marker_particles_probe.rs
+++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs
@@ -49,7 +49,7 @@ pub fn main() -> Result<()> {
}
}
}
- let mut engine = ParticleEngine::new(root, &HashMap::new());
+ let mut engine = ParticleEngine::new(root, &HashMap::new(), Default::default());
let mut out = BufWriter::new(File::create(&args[2])?);
for line in BufReader::new(File::open(&args[1])?).lines() {
let case: Value = serde_json::from_str(&line?)?;
diff --git a/crates/horizon-client/examples/probe/particle_providers_probe.rs b/crates/horizon-client/examples/probe/particle_providers_probe.rs
index c8cd9d88d..067648e95 100644
--- a/crates/horizon-client/examples/probe/particle_providers_probe.rs
+++ b/crates/horizon-client/examples/probe/particle_providers_probe.rs
@@ -152,7 +152,7 @@ pub fn main() -> Result<()> {
world(&assets, &facts, false, true)?,
world(&assets, &facts, true, true)?,
];
- let mut engine = ParticleEngine::new(root, &HashMap::new());
+ let mut engine = ParticleEngine::new(root, &HashMap::new(), Default::default());
for (ty, item) in [
(ParticleType::ItemSlime, "item_slime_ball"),
(ParticleType::ItemSnowball, "item_snowball"),
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 653a1d038..cfb3ad433 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -11690,7 +11690,11 @@ impl<'a> Game<'a> {
let inventory = vec![None; 36];
let now = Instant::now();
let look = options.look;
- let particles = horizon_client::particles::ParticleEngine::new(&root, &gui.atlas.sprites);
+ let particles = horizon_client::particles::ParticleEngine::new(
+ &root,
+ &gui.atlas.sprites,
+ gui.atlas.translucent.clone(),
+ );
Ok(Game {
res: res.clone(),
rest_loader: None,
diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs
index a848d36a5..6af750b62 100644
--- a/crates/horizon-client/src/gfx.rs
+++ b/crates/horizon-client/src/gfx.rs
@@ -35,7 +35,7 @@ fn entity_shader() -> String {
mod entity_batch;
mod weather;
use entity_batch::EntityBatch;
-pub use entity_batch::{SHADOW_OVERLAY, WATER_MASK_OVERLAY};
+pub use entity_batch::{SHADOW_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY};
/// Window.getAppropriateLineWidth, in framebuffer pixels.
pub fn outline_width(width: u32) -> f32 {
@@ -3362,6 +3362,7 @@ impl Renderer {
translucent_crumbling_quads,
water_mask_quads,
shadow_quads,
+ translucent_particle_quads,
] = self.entity_batch.update(
frame.entities,
frame.additive,
@@ -3373,7 +3374,8 @@ impl Renderer {
+ crumbling_quads
+ translucent_crumbling_quads
+ water_mask_quads
- + shadow_quads;
+ + shadow_quads
+ + translucent_particle_quads;
let cloud_quads = if let Some(input) = &frame.clouds {
let (rebuilt, uniform) =
crate::spans::time("clouds", || self.cloud_mesh.prepare(input));
@@ -3827,6 +3829,22 @@ impl Renderer {
);
}
}
+ // LevelRenderer.executeTranslucentAfterTerrain: vanilla's
+ // translucent particle layer draws after translucent terrain —
+ // the quads write depth, so before it they would hide the glass
+ // or water behind them.
+ if translucent_particle_quads > 0 {
+ pass.set_pipeline(&self.entity_pipeline);
+ pass.set_bind_group(0, &self.entity_group, &[]);
+ pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
+ pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
+ pass.draw_indexed(
+ 0..translucent_particle_quads * 6,
+ ((world_quads - translucent_particle_quads) * 4) as i32,
+ 0..1,
+ );
+ pass.set_bind_group(0, &self.group, &[]);
+ }
// LevelRenderer.executeClassicTransparency: translucent targets'
// outlines follow terrain, so its blending cannot wash them out.
if outline_edges > 0 && frame.outline_after_terrain {
@@ -4316,14 +4334,23 @@ mod tests {
normal: [0; 4],
}; 4]
};
- let entities: Vec<_> = [(0, 0), (14, 9), (4, 1), (11, 2), (7, 3), (4, 4), (12, 7)]
- .into_iter()
- .flat_map(|(layer, id)| quad(layer, id))
- .collect();
+ let entities: Vec<_> = [
+ (0, 0),
+ (14, 9),
+ (4, 1),
+ (11, 2),
+ (15, 10),
+ (7, 3),
+ (4, 4),
+ (12, 7),
+ ]
+ .into_iter()
+ .flat_map(|(layer, id)| quad(layer, id))
+ .collect();
let mut batch = super::EntityBatch::default();
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8));
let vertices = &batch.combined;
- assert_eq!(counts, [4, 1, 1, 0, 1]);
+ assert_eq!(counts, [4, 1, 1, 0, 1, 1]);
assert_eq!(
vertices
.as_chunks::<4>()
@@ -4331,7 +4358,7 @@ mod tests {
.iter()
.map(|q| q[0].light)
.collect::>(),
- [0, 1, 3, 4, 2, 7, 9, 5, 6, 8]
+ [0, 1, 3, 4, 2, 7, 9, 10, 5, 6, 8]
);
}
#[test]
diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs
index 56ffb04b9..8153699fc 100644
--- a/crates/horizon-client/src/gfx/entity_batch.rs
+++ b/crates/horizon-client/src/gfx/entity_batch.rs
@@ -3,13 +3,16 @@ use super::Vertex;
/// Entity materials by a quad's overlay (`Vertex::layer`), in draw order:
/// ordinary entities, breaking cracks (11), translucent breaking cracks (12),
-/// the boat water mask (13, `RenderPipelines.WATER_MASK`) and entity shadows
-/// (14, `RenderPipelines.ENTITY_SHADOW`).
-const MATERIALS: usize = 5;
+/// the boat water mask (13, `RenderPipelines.WATER_MASK`), entity shadows
+/// (14, `RenderPipelines.ENTITY_SHADOW`) and translucent-layer particles (15,
+/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`).
+const MATERIALS: usize = 6;
/// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`).
pub const WATER_MASK_OVERLAY: u32 = 13;
/// The overlay of entity shadow quads (`RenderTypes.entityShadow`).
pub const SHADOW_OVERLAY: u32 = 14;
+/// The overlay of translucent-layer particles (`SingleQuadParticle.Layer.translucent`).
+pub const TRANSLUCENT_PARTICLE_OVERLAY: u32 = 15;
#[derive(Default)]
pub(super) struct EntityBatch {
@@ -41,6 +44,7 @@ impl EntityBatch {
12 => 2,
WATER_MASK_OVERLAY => 3,
SHADOW_OVERLAY => 4,
+ TRANSLUCENT_PARTICLE_OVERLAY => 5,
_ => 0,
};
self.buckets[material][counts[material]] = index;
@@ -92,13 +96,14 @@ mod tests {
) -> (Vec, [u32; MATERIALS]) {
let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len());
let mut counts = [0; MATERIALS];
- for (i, layer) in [0, 11, 12, 13, 14].into_iter().enumerate() {
+ for (i, layer) in [0, 11, 12, 13, 14, 15].into_iter().enumerate() {
for quad in entities.as_chunks::<4>().0 {
let material = match quad[0].layer {
11 => 11,
12 => 12,
13 => 13,
14 => 14,
+ 15 => 15,
_ => 0,
};
if material == layer {
@@ -118,7 +123,7 @@ mod tests {
pos: [index as f32, 2.0, 3.0],
uv: [index as f32, 5.0],
layer: if mixed {
- [7, 11, 14, 12, 4, 13, 0][index / 4 % 7]
+ [7, 11, 14, 12, 4, 13, 15, 0][index / 4 % 8]
} else {
0
},
diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs
index 89d1b1c3c..5626359c8 100644
--- a/crates/horizon-client/src/hud.rs
+++ b/crates/horizon-client/src/hud.rs
@@ -3,7 +3,7 @@
//! GUI scale is applied when drawing).
use crate::Result;
use std::{
- collections::HashMap,
+ collections::{HashMap, HashSet},
fs,
path::{Path, PathBuf},
};
@@ -58,6 +58,9 @@ pub struct HudAtlas {
pub width: u32,
pub height: u32,
pub sprites: HashMap,
+ /// Sprites with a 0 < alpha < 255 texel (`SpriteContents.transparency().hasTranslucent`),
+ /// which puts their particles on vanilla's translucent layer.
+ pub translucent: HashSet,
/// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others
/// sample as vanilla's defaults (nearest, repeat).
pub flags: HashMap,
@@ -459,7 +462,16 @@ impl HudAtlas {
let height = (glyph_region + GLYPH_ROWS).next_multiple_of(1024);
let mut pixels = vec![0u8; (width * height * 4) as usize];
let mut sprites = HashMap::new();
+ let mut translucent = HashSet::new();
for ((name, w, h, data), (px, py)) in images.iter().zip(placements) {
+ if data
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .any(|p| p[3] != 0 && p[3] != 255)
+ {
+ translucent.insert(name.clone());
+ }
for row in 0..*h {
let src = &data[(row * w * 4) as usize..((row + 1) * w * 4) as usize];
let dst = (((py + row) * width + px) * 4) as usize;
@@ -524,6 +536,7 @@ impl HudAtlas {
width,
height,
sprites,
+ translucent,
flags,
fire_animations,
font,
diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs
index 0d4f4d623..62127808a 100644
--- a/crates/horizon-client/src/particles.rs
+++ b/crates/horizon-client/src/particles.rs
@@ -18,7 +18,10 @@ use horizon_core::{
random::{LegacyRandom, RandomSource},
};
use horizon_world::block_collision::BlockCollisionRegistry;
-use std::{collections::HashMap, path::Path};
+use std::{
+ collections::{HashMap, HashSet},
+ path::Path,
+};
macro_rules! particle_types {
($($variant:ident = $name:literal),* $(,)?) => {
@@ -196,6 +199,33 @@ impl ParticleType {
| Self::OminousSpawning
)
}
+ /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class
+ /// hardcodes the translucent layer, drawn after translucent terrain.
+ /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their
+ /// layer from the sprite instead (`Layer.bySprite`); see the `translucent`
+ /// sprite set on the engine.
+ pub fn translucent_layer(self) -> bool {
+ match self {
+ // CampfireSmokeParticle.
+ Self::CampfireCosySmoke | Self::CampfireSignalSmoke
+ // PlayerCloudParticle.
+ | Self::Cloud | Self::Sneeze
+ // SpellParticle.
+ | Self::Effect | Self::InstantEffect | Self::EntityEffect
+ | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen
+ // EmissiveRisingParticle.
+ | Self::Soul | Self::SculkSoul
+ // SculkChargeParticle, SculkChargePopParticle, ShriekParticle,
+ // VibrationSignalParticle, FireflyParticle, OverlayParticle.
+ | Self::SculkCharge | Self::SculkChargePop | Self::Shriek
+ | Self::Vibration | Self::Firefly | Self::Flash
+ // SimpleAnimatedParticle and its subclasses: EndRodParticle,
+ // SparkParticle (firework), SquidInkParticle, TotemParticle.
+ | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk
+ | Self::TotemOfUndying => true,
+ _ => false,
+ }
+ }
}
/// `ParticleOptions` with the parameters of the option classes used here.
@@ -1148,6 +1178,9 @@ pub struct ParticleEngine {
names: Vec,
rects: Vec>,
atlas: HashMap,
+ /// `SingleQuadParticle.Layer.bySprite`: named sprites whose texels include
+ /// 0 < alpha < 255 render on vanilla's translucent particle layer.
+ translucent: HashSet,
sets: HashMap,
set_sprites: Vec>,
/// `TrackingEmitter`s: particle type, entity feet position, width, height, ticks left.
@@ -1167,7 +1200,7 @@ pub struct ParticleEngine {
/// `ParticleGroup.MAX_PARTICLES` (per render group; one group here).
const MAX_PARTICLES: usize = 16384;
impl ParticleEngine {
- pub fn new(root: &Path, atlas: &HashMap) -> Self {
+ pub fn new(root: &Path, atlas: &HashMap, translucent: HashSet) -> Self {
let mut engine = Self {
particles: Vec::new(),
pending: Vec::new(),
@@ -1179,6 +1212,7 @@ impl ParticleEngine {
names: Vec::new(),
rects: Vec::new(),
atlas: atlas.clone(),
+ translucent,
sets: HashMap::new(),
set_sprites: Vec::new(),
emitters: Vec::new(),
@@ -3765,6 +3799,13 @@ impl ParticleEngine {
Sprite::Named(name) => self.atlas.get(name).copied(),
};
let Some(r) = rect else { continue };
+ // `SubmitNodeCollection.submitQuadParticleGroup`: the translucent
+ // layer draws after translucent terrain, so a crumb of stained
+ // glass cannot hide the glass behind it (`getLayer`).
+ let layer = match &p.sprite {
+ Sprite::Index(_) => p.ty.translucent_layer(),
+ Sprite::Named(name) => self.translucent.contains(name),
+ };
let a = f64::from(partial);
let pos = DVec3::new(
p.previous[0] + (p.position[0] - p.previous[0]) * a,
@@ -3867,7 +3908,11 @@ impl ParticleEngine {
normal: [0; 4],
pos: v.to_array(),
uv,
- layer: 0,
+ layer: if layer {
+ crate::gfx::TRANSLUCENT_PARTICLE_OVERLAY
+ } else {
+ 0
+ },
color,
light,
});
@@ -3891,7 +3936,7 @@ mod tests {
#[test]
fn egg_teleport_unpacks_offsets_and_preserves_seeded_draw_order() {
- let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new());
+ let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), HashSet::new());
engine.seed_randoms(0, 0, 0);
// Destination offset (-15, 7, 15); the unused top byte is ignored.
engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0);
@@ -3916,7 +3961,7 @@ mod tests {
#[test]
fn consume_teleport_unpacks_offsets_within_127() {
- let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new());
+ let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), HashSet::new());
engine.seed_randoms(0, 0, 0);
// TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition
// of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4).
@@ -3941,7 +3986,8 @@ mod tests {
(2, 0, 99_413_408_083_437),
] {
for distant in [false, true] {
- let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new());
+ let mut engine =
+ ParticleEngine::new(Path::new(""), &HashMap::new(), HashSet::new());
engine.seed_randoms(0, 0, 0);
if distant {
engine.camera = [1000.0; 3];
From be378bb77361b611b9451f76033daf97e0c8d75e Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 10:44:32 +0100
Subject: [PATCH 11/88] Particles: vault connections are translucent, shadows
keep their range
- FlyTowardsPositionParticle puts vault_connection on the translucent
layer: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque.
- The shadow draw started at world_quads - shadow_quads; with the new
bucket after it, that drew translucent particles with the shadow
pipeline and dropped as many shadows.
- One atlas lookup per named-sprite particle and frame: the engine keeps
each sprite's layer beside its rect instead of hashing the name twice.
Co-Authored-By: Claude Opus 5.5
---
.../examples/probe/marker_particles_probe.rs | 2 +-
.../probe/particle_providers_probe.rs | 2 +-
crates/horizon-client/src/game.rs | 2 +-
crates/horizon-client/src/gfx.rs | 2 +-
crates/horizon-client/src/particles.rs | 45 ++++++++++---------
5 files changed, 29 insertions(+), 24 deletions(-)
diff --git a/crates/horizon-client/examples/probe/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs
index 6b05af356..72ebaff22 100644
--- a/crates/horizon-client/examples/probe/marker_particles_probe.rs
+++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs
@@ -49,7 +49,7 @@ pub fn main() -> Result<()> {
}
}
}
- let mut engine = ParticleEngine::new(root, &HashMap::new(), Default::default());
+ let mut engine = ParticleEngine::new(root, &HashMap::new(), &Default::default());
let mut out = BufWriter::new(File::create(&args[2])?);
for line in BufReader::new(File::open(&args[1])?).lines() {
let case: Value = serde_json::from_str(&line?)?;
diff --git a/crates/horizon-client/examples/probe/particle_providers_probe.rs b/crates/horizon-client/examples/probe/particle_providers_probe.rs
index 067648e95..68f23f3af 100644
--- a/crates/horizon-client/examples/probe/particle_providers_probe.rs
+++ b/crates/horizon-client/examples/probe/particle_providers_probe.rs
@@ -152,7 +152,7 @@ pub fn main() -> Result<()> {
world(&assets, &facts, false, true)?,
world(&assets, &facts, true, true)?,
];
- let mut engine = ParticleEngine::new(root, &HashMap::new(), Default::default());
+ let mut engine = ParticleEngine::new(root, &HashMap::new(), &Default::default());
for (ty, item) in [
(ParticleType::ItemSlime, "item_slime_ball"),
(ParticleType::ItemSnowball, "item_snowball"),
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index cfb3ad433..f6b1bf828 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -11693,7 +11693,7 @@ impl<'a> Game<'a> {
let particles = horizon_client::particles::ParticleEngine::new(
&root,
&gui.atlas.sprites,
- gui.atlas.translucent.clone(),
+ &gui.atlas.translucent,
);
Ok(Game {
res: res.clone(),
diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs
index 6af750b62..f8cd8acd8 100644
--- a/crates/horizon-client/src/gfx.rs
+++ b/crates/horizon-client/src/gfx.rs
@@ -3761,7 +3761,7 @@ impl Renderer {
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..shadow_quads * 6,
- ((world_quads - shadow_quads) * 4) as i32,
+ ((world_quads - translucent_particle_quads - shadow_quads) * 4) as i32,
0..1,
);
pass.set_bind_group(0, &self.group, &[]);
diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs
index 62127808a..be7f32551 100644
--- a/crates/horizon-client/src/particles.rs
+++ b/crates/horizon-client/src/particles.rs
@@ -222,7 +222,9 @@ impl ParticleType {
// SimpleAnimatedParticle and its subclasses: EndRodParticle,
// SparkParticle (firework), SquidInkParticle, TotemParticle.
| Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk
- | Self::TotemOfUndying => true,
+ | Self::TotemOfUndying
+ // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque.
+ | Self::VaultConnection => true,
_ => false,
}
}
@@ -1177,10 +1179,9 @@ pub struct ParticleEngine {
pub requested: Option>,
names: Vec,
rects: Vec>,
- atlas: HashMap,
- /// `SingleQuadParticle.Layer.bySprite`: named sprites whose texels include
- /// 0 < alpha < 255 render on vanilla's translucent particle layer.
- translucent: HashSet,
+ /// Each named sprite, and whether `SingleQuadParticle.Layer.bySprite` puts
+ /// it on the translucent layer (a texel with 0 < alpha < 255).
+ atlas: HashMap,
sets: HashMap,
set_sprites: Vec>,
/// `TrackingEmitter`s: particle type, entity feet position, width, height, ticks left.
@@ -1200,7 +1201,7 @@ pub struct ParticleEngine {
/// `ParticleGroup.MAX_PARTICLES` (per render group; one group here).
const MAX_PARTICLES: usize = 16384;
impl ParticleEngine {
- pub fn new(root: &Path, atlas: &HashMap, translucent: HashSet) -> Self {
+ pub fn new(root: &Path, atlas: &HashMap, translucent: &HashSet) -> Self {
let mut engine = Self {
particles: Vec::new(),
pending: Vec::new(),
@@ -1211,8 +1212,10 @@ impl ParticleEngine {
requested: None,
names: Vec::new(),
rects: Vec::new(),
- atlas: atlas.clone(),
- translucent,
+ atlas: atlas
+ .iter()
+ .map(|(name, &rect)| (name.clone(), (rect, translucent.contains(name))))
+ .collect(),
sets: HashMap::new(),
set_sprites: Vec::new(),
emitters: Vec::new(),
@@ -1254,7 +1257,7 @@ impl ParticleEngine {
return i as u32;
}
self.names.push(name.to_owned());
- self.rects.push(self.atlas.get(name).copied());
+ self.rects.push(self.atlas.get(name).map(|&(rect, _)| rect));
(self.names.len() - 1) as u32
}
pub fn len(&self) -> usize {
@@ -3794,18 +3797,20 @@ impl ParticleEngine {
{
continue;
}
- let rect = match &p.sprite {
- Sprite::Index(i) => self.rects.get(*i as usize).copied().flatten(),
- Sprite::Named(name) => self.atlas.get(name).copied(),
- };
- let Some(r) = rect else { continue };
// `SubmitNodeCollection.submitQuadParticleGroup`: the translucent
// layer draws after translucent terrain, so a crumb of stained
// glass cannot hide the glass behind it (`getLayer`).
- let layer = match &p.sprite {
- Sprite::Index(_) => p.ty.translucent_layer(),
- Sprite::Named(name) => self.translucent.contains(name),
+ let (rect, layer) = match &p.sprite {
+ Sprite::Index(i) => (
+ self.rects.get(*i as usize).copied().flatten(),
+ p.ty.translucent_layer(),
+ ),
+ Sprite::Named(name) => match self.atlas.get(name) {
+ Some(&(rect, translucent)) => (Some(rect), translucent),
+ None => (None, false),
+ },
};
+ let Some(r) = rect else { continue };
let a = f64::from(partial);
let pos = DVec3::new(
p.previous[0] + (p.position[0] - p.previous[0]) * a,
@@ -3936,7 +3941,7 @@ mod tests {
#[test]
fn egg_teleport_unpacks_offsets_and_preserves_seeded_draw_order() {
- let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), HashSet::new());
+ let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
engine.seed_randoms(0, 0, 0);
// Destination offset (-15, 7, 15); the unused top byte is ignored.
engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0);
@@ -3961,7 +3966,7 @@ mod tests {
#[test]
fn consume_teleport_unpacks_offsets_within_127() {
- let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), HashSet::new());
+ let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
engine.seed_randoms(0, 0, 0);
// TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition
// of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4).
@@ -3987,7 +3992,7 @@ mod tests {
] {
for distant in [false, true] {
let mut engine =
- ParticleEngine::new(Path::new(""), &HashMap::new(), HashSet::new());
+ ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
engine.seed_randoms(0, 0, 0);
if distant {
engine.camera = [1000.0; 3];
From 0bc85843ce0d9672c6990345af6ffd4e4b180993 Mon Sep 17 00:00:00 2001
From: socksprox
Date: Sun, 25 Oct 2026 00:19:47 +0200
Subject: [PATCH 12/88] Client: remote players keep their skins instead of
falling back
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
skins::unpack discarded a profile's whole textures payload when any one
entry lacked "url" or pointed outside the texture services' domains, so
a player with e.g. an unusual cape lost their skin too; it now drops only
the offending texture. The 32 skin atlas slots evicted past players back
to defaults on busy servers — now 128. A dimension reset (join game or
respawn onto another world) now also clears the entity-id→profile map so
a re-used entity id can't pin the wrong skin or name to a player, and the
nametag join falls back to the player-list entry's name.
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
crates/horizon-client/src/game/remote.rs | 12 +++++++++++-
crates/horizon-client/src/hud.rs | 4 +++-
crates/horizon-client/src/skins.rs | 21 +++++++++++----------
3 files changed, 25 insertions(+), 12 deletions(-)
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 5a71b13a8..36122d42a 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -1006,6 +1006,9 @@ impl Game<'_> {
r.stepped.clear();
r.head_lerps.clear();
r.pending_items.clear();
+ // The entity ids are the old world's; the new dimension's
+ // player entities re-map to their profiles on AddEntity.
+ r.level_players.clear();
// A new ClientLevel: a new chunk storage, centred on 0, 0.
r.chunk_center = (0, 0);
}
@@ -5065,7 +5068,14 @@ impl Game<'_> {
r.level_players
.iter()
.filter(|(_, uuid)| **uuid != r.profile)
- .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone())))
+ .filter_map(|(id, uuid)| {
+ let name = r
+ .players
+ .get(uuid)
+ .cloned()
+ .or_else(|| r.tab_players.get(uuid).map(|t| t.name.clone()))?;
+ Some((*id as u32, name))
+ })
.collect()
}
/// `ClientClockManager.tick`: the clock moves on by the game time that
diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs
index 89d1b1c3c..90a8b346c 100644
--- a/crates/horizon-client/src/hud.rs
+++ b/crates/horizon-client/src/hud.rs
@@ -78,7 +78,9 @@ pub const MAP_SLOTS: usize = 256;
/// The atlas slot the minimap extra draws into.
pub const MINIMAP_SPRITE: &str = "horizon/minimap";
/// Atlas slots for downloaded player skins (`skins/`), 64x64 each.
-pub const SKIN_SLOTS: usize = 32;
+/// Vanilla registers a texture per skin; too few slots evict a busy
+/// server's players back to their default skins.
+pub const SKIN_SLOTS: usize = 128;
/// Reused by the visible rows of the classic world selector.
pub const WORLD_ICON_SLOTS: usize = 32;
/// Atlas slots for the pack icons on the pack screen, one per icon drawn
diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs
index 9014032c4..0cf9cc8a2 100644
--- a/crates/horizon-client/src/skins.rs
+++ b/crates/horizon-client/src/skins.rs
@@ -92,22 +92,23 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture
..empty.clone()
};
for (kind, texture) in textures {
- let Some(url) = texture.get("url").and_then(|u| u.as_str()) else {
- return empty;
- };
- let allowed = valid_uris
- .iter()
- .any(|u| url.starts_with(&u.replace("{textureId}", "")));
- if !allowed {
- return empty;
- }
let slot = match kind.as_str() {
"SKIN" => &mut out.skin,
"CAPE" => &mut out.cape,
"ELYTRA" => &mut out.elytra,
_ => continue,
};
- *slot = Some(url.to_owned());
+ // One bad entry (no `url`, or a URL outside the texture services'
+ // domains) drops only that texture, not the whole payload.
+ let Some(url) = texture.get("url").and_then(|u| u.as_str()) else {
+ continue;
+ };
+ let allowed = valid_uris
+ .iter()
+ .any(|u| url.starts_with(&u.replace("{textureId}", "")));
+ if allowed {
+ *slot = Some(url.to_owned());
+ }
}
out
}
From 3740de5116dbf9322e39d18c3ce0777d087d0401 Mon Sep 17 00:00:00 2001
From: socksprox
Date: Sun, 25 Oct 2026 13:40:07 +0100
Subject: [PATCH 13/88] Launcher: pin the macOS title bar to the chosen
appearance
The launcher's Appearance setting darkened the page but not the window's native chrome: NSWindow keeps the system appearance, so a launcher set to Dark still drew a light title bar on a light desktop. apply_appearance (titlebar.rs) pins the NSWindow's appearance to the choice at startup and when the setting changes; System clears the pin so the chrome follows the computer again.
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
launcher/Cargo.lock | 2 ++
launcher/Cargo.toml | 4 ++++
launcher/src/main.rs | 4 ++++
launcher/src/titlebar.rs | 49 +++++++++++++++++++++++++++++++++++++++-
4 files changed, 58 insertions(+), 1 deletion(-)
diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock
index 5155420e0..922a92f2f 100644
--- a/launcher/Cargo.lock
+++ b/launcher/Cargo.lock
@@ -2680,8 +2680,10 @@ dependencies = [
"horizon-theme",
"image",
"keyring",
+ "objc2-app-kit",
"oo7",
"pulldown-cmark",
+ "raw-window-handle",
"self-replace",
"serde",
"serde_json",
diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml
index a402d0e28..570e2bd75 100644
--- a/launcher/Cargo.toml
+++ b/launcher/Cargo.toml
@@ -48,6 +48,10 @@ oo7 = { version = "0.5", default-features = false, features = ["async-std", "nat
futures-lite = "2"
[target.'cfg(target_os = "macos")'.dependencies]
keyring = { version = "3", features = ["apple-native"] }
+# Painting the window's title bar dark or light (titlebar::apply_appearance): crates already in
+# the lockfile through gpui and wgpu.
+objc2-app-kit = { version = "0.3", default-features = false, features = ["NSAppearance", "NSView", "NSWindow"] }
+raw-window-handle = "0.6"
[target.'cfg(target_os = "windows")'.dependencies]
keyring = { version = "3", features = ["windows-native"] }
diff --git a/launcher/src/main.rs b/launcher/src/main.rs
index 0bcbc4011..ebde171e5 100644
--- a/launcher/src/main.rs
+++ b/launcher/src/main.rs
@@ -265,6 +265,9 @@ impl Launcher {
{
settings.selected = installed.first().cloned();
}
+ // Pin the window's chrome (macOS title bar) to the choice before the theme reads
+ // `window.appearance()`, so both draw the same look.
+ titlebar::apply_appearance(window, settings.appearance);
let mut this = Self {
theme: Theme::for_appearance(settings.appearance, window.appearance()),
page: Page::from_env(),
@@ -2482,6 +2485,7 @@ impl Launcher {
let _ = this.update(cx, |this, cx| {
this.settings.appearance = choice;
this.settings.save();
+ titlebar::apply_appearance(window, choice);
this.theme = Theme::for_appearance(choice, window.appearance());
cx.notify();
});
diff --git a/launcher/src/titlebar.rs b/launcher/src/titlebar.rs
index 3c2a78ea4..2e6445091 100644
--- a/launcher/src/titlebar.rs
+++ b/launcher/src/titlebar.rs
@@ -1,6 +1,8 @@
-//! Custom Windows chrome. Other platforms keep their native window decorations.
+//! Custom Windows chrome. Other platforms keep their native window decorations; on macOS,
+//! `apply_appearance` repaints that chrome (the title bar) to match the chosen look.
use crate::theme::Theme;
use gpui::{Div, TitlebarOptions, Window};
+use horizon_launcher::backend::Appearance;
/// Whether the launcher draws its own title bar (`render`) rather than the system.
pub const DRAWN: bool = cfg!(target_os = "windows");
@@ -18,6 +20,51 @@ pub fn render(_theme: &Theme, _window: &Window) -> Option {
None
}
+/// macOS keeps the window's appearance on the system setting, so a launcher set to Dark still
+/// draws a light title bar on a light desktop. Pin the NSWindow's appearance to the choice
+/// instead (`System` clears the pin, handing the chrome back to the system), honouring the same
+/// `HORIZON_LAUNCHER_APPEARANCE` override the theme does. Other platforms' chrome already
+/// follows the setting (ours is drawn, Windows and Linux follow the system either way).
+#[cfg(target_os = "macos")]
+pub fn apply_appearance(window: &Window, choice: Appearance) {
+ use objc2_app_kit::{
+ NSAppearance, NSAppearanceCustomization, NSAppearanceName, NSAppearanceNameAqua,
+ NSAppearanceNameDarkAqua, NSView,
+ };
+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+
+ // Reading AppKit's name constants is unsafe to rustc only (`use of extern static`).
+ let name: Option<&'static NSAppearanceName> = unsafe {
+ match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() {
+ Ok("light") => Some(NSAppearanceNameAqua),
+ Ok("dark") => Some(NSAppearanceNameDarkAqua),
+ _ => match choice {
+ Appearance::Dark => Some(NSAppearanceNameDarkAqua),
+ Appearance::Light => Some(NSAppearanceNameAqua),
+ Appearance::System => None,
+ },
+ }
+ };
+ // The trait, not `Window::window_handle` (which is gpui's own `AnyWindowHandle`).
+ let Ok(handle) = HasWindowHandle::window_handle(window) else {
+ return;
+ };
+ let RawWindowHandle::AppKit(appkit) = handle.as_raw() else {
+ return;
+ };
+ // The handle is the window's content view; its `window` is the NSWindow itself. Both outlive
+ // this call.
+ let view = unsafe { appkit.ns_view.cast::
().as_ref() };
+ let Some(native) = view.window() else {
+ return;
+ };
+ let appearance = name.and_then(NSAppearance::appearanceNamed);
+ native.setAppearance(appearance.as_deref());
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn apply_appearance(_: &Window, _: Appearance) {}
+
#[cfg(target_os = "windows")]
mod windows {
use super::*;
From 9e21868dfa012b3a46d3242d03e56845fb6fb5c5 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 13:46:45 +0100
Subject: [PATCH 14/88] Potions keep their potion across the connection
A server's client (single player on the server thread, LAN guests, a
dedicated server's players) saw every potion as an "Uncraftable Potion"
in the water colour: the server never wrote `minecraft:potion_contents`
and the client read past it. A potion taken from the creative menu also
reached the server without its potion, so it splashed as water.
PotionContents now goes as vanilla's stream codec writes it: the potion
by its `minecraft:potion` id and the custom colour, with the custom
effects and name kept as their bytes. The server writes it for every
stack it sends, the client reads it into the item's components, and a
creative pick and the server's read of it keep the potion too.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game/lan_actions.rs | 7 ++
crates/horizon-client/src/game/remote.rs | 24 +++++
crates/horizon-client/src/lan/guest.rs | 34 +++++++
crates/horizon-protocol/src/item.rs | 90 +++++++++++++++++++
crates/horizon-protocol/src/item/skip.rs | 8 +-
5 files changed, 158 insertions(+), 5 deletions(-)
diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs
index 2c7019c73..4964bc687 100644
--- a/crates/horizon-client/src/game/lan_actions.rs
+++ b/crates/horizon-client/src/game/lan_actions.rs
@@ -1231,6 +1231,13 @@ impl Game<'_> {
}
}
}
+ if let Some(Component::Potion {
+ potion: Some(id), ..
+ }) = s.component(component::POTION_CONTENTS)
+ && let Some(potion) = host.hub.registry_name("minecraft:potion", *id)
+ {
+ out = out.with_potion(potion);
+ }
Some(out)
}
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 5a71b13a8..c723400a8 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -672,6 +672,16 @@ impl Game<'_> {
("mob_factor", Tag::Float(v[5].to_bits())),
]),
Component::Profile(p) => profile_tag(p),
+ // PotionContents' NBT: the potion by name and the custom colour.
+ Component::Potion { potion, color, .. } => {
+ let potion = potion.and_then(|id| r.builtin.get("minecraft:potion")?.name(id));
+ Tag::compound(
+ potion
+ .map(|name| ("potion", Tag::String(name.into())))
+ .into_iter()
+ .chain(color.map(|c| ("custom_color", Tag::Int(c)))),
+ )
+ }
// ItemStackTemplate.CODEC: id, count and components.
Component::Stacks(stacks) => Tag::List(
stacks
@@ -733,6 +743,20 @@ impl Game<'_> {
fn to_network(&self, s: &Option) -> Option {
let s = s.as_ref()?;
let mut stack = Stack::new(self.item_id(&s.item), s.count as i32);
+ // A creative pick keeps its potion (PotionContents by its builtin id).
+ if let Some(id) = s.potion().and_then(|p| {
+ let potions = self.remote.as_ref()?.builtin.get("minecraft:potion")?;
+ potions.id(&horizon_world::datafix::dynamic::namespaced(p))
+ }) {
+ stack.added.push((
+ horizon_protocol::item::component::POTION_CONTENTS,
+ horizon_protocol::item::Component::Potion {
+ potion: Some(id),
+ color: None,
+ rest: Vec::new(),
+ },
+ ));
+ }
if s.damage > 0 {
stack.added.push((
horizon_protocol::item::component::DAMAGE,
diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs
index 440b58284..bbab454d7 100644
--- a/crates/horizon-client/src/lan/guest.rs
+++ b/crates/horizon-client/src/lan/guest.rs
@@ -521,6 +521,22 @@ fn network_stack(
horizon_protocol::item::Component::Int(i32::from(mode)),
));
}
+ // PotionContents: the potion by its `minecraft:potion` id.
+ if let Some(id) = (d.potion.as_deref()).and_then(|potion| {
+ synced_id(
+ "minecraft:potion",
+ &horizon_world::datafix::dynamic::namespaced(potion),
+ )
+ }) {
+ stack.added.push((
+ horizon_protocol::item::component::POTION_CONTENTS,
+ horizon_protocol::item::Component::Potion {
+ potion: Some(id),
+ color: None,
+ rest: Vec::new(),
+ },
+ ));
+ }
// A loaded crossbow's ammunition.
if !d.charged.is_empty() {
let charged = d
@@ -573,6 +589,24 @@ mod tests {
use super::*;
use horizon_protocol::item::{Component, component};
+ #[test]
+ fn potions_go_as_potion_registry_ids() {
+ let synced_id = |registry: &str, name: &str| match (registry, name) {
+ ("minecraft:potion", "minecraft:swiftness") => Some(14),
+ _ => None,
+ };
+ let potion = ItemStack::new("minecraft:splash_potion", 1).with_potion("swiftness");
+ let stack = stack_to_network(|_| 7, synced_id, &Some(potion)).unwrap();
+ assert_eq!(
+ stack.component(component::POTION_CONTENTS),
+ Some(&Component::Potion {
+ potion: Some(14),
+ color: None,
+ rest: Vec::new(),
+ })
+ );
+ }
+
#[test]
fn trims_go_as_synced_registry_references() {
let mut chestplate = ItemStack::new("minecraft:diamond_chestplate", 1);
diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs
index 6b6b845f8..2c04b5c61 100644
--- a/crates/horizon-protocol/src/item.rs
+++ b/crates/horizon-protocol/src/item.rs
@@ -35,6 +35,7 @@ pub mod component {
pub const MAP_ID: i32 = 48;
pub const MAP_POST_PROCESSING: i32 = 50;
pub const CHARGED_PROJECTILES: i32 = 51;
+ pub const POTION_CONTENTS: i32 = 53;
pub const WRITABLE_BOOK_CONTENT: i32 = 56;
pub const WRITTEN_BOOK_CONTENT: i32 = 57;
pub const TRIM: i32 = 58;
@@ -65,6 +66,13 @@ pub enum Component {
Lore(Vec),
Enchantments(Vec<(i32, i32)>),
AttackRange([f32; 6]),
+ /// `PotionContents`: the potion's `minecraft:potion` id and the custom
+ /// colour; the custom effects and name stay their encoded bytes.
+ Potion {
+ potion: Option,
+ color: Option,
+ rest: Vec,
+ },
Profile(Profile),
CustomModelData {
floats: Vec,
@@ -162,6 +170,22 @@ impl Component {
.collect::>()?,
)
}
+ POTION_CONTENTS => {
+ let potion = if r.bool()? { Some(r.varint()?) } else { None };
+ let color = if r.bool()? { Some(r.i32()?) } else { None };
+ let start = r.position();
+ skip::potion_effects_and_name(r)?;
+ // No custom effects and no name: an empty tail.
+ let rest = match r.since(start) {
+ [0, 0] => Vec::new(),
+ bytes => bytes.to_vec(),
+ };
+ Self::Potion {
+ potion,
+ color,
+ rest,
+ }
+ }
ATTACK_RANGE => {
let mut values = [0.0f32; 6];
for v in &mut values {
@@ -283,6 +307,27 @@ impl Component {
}
}
Self::AttackRange(values) => values.iter().for_each(|v| w.f32(*v)),
+ Self::Potion {
+ potion,
+ color,
+ rest,
+ } => {
+ w.bool(potion.is_some());
+ if let Some(id) = potion {
+ w.varint(*id);
+ }
+ w.bool(color.is_some());
+ if let Some(color) = color {
+ w.i32(*color);
+ }
+ // An empty tail is no custom effects and no name.
+ if rest.is_empty() {
+ w.varint(0);
+ w.bool(false);
+ } else {
+ w.bytes(rest);
+ }
+ }
Self::Profile(p) => {
w.u8(0);
w.bool(p.name.is_some());
@@ -532,6 +577,51 @@ mod tests {
assert_eq!(r.remaining(), 0);
}
+ #[test]
+ fn potion_contents_round_trip() {
+ let mut arrow = Stack::new(7, 3);
+ arrow.added.push((
+ component::POTION_CONTENTS,
+ Component::Potion {
+ potion: Some(31),
+ color: None,
+ rest: Vec::new(),
+ },
+ ));
+ round::, Slot>(Some(arrow));
+ // A custom colour, one custom effect (speed II for 600 ticks, shown,
+ // no hidden effect) and a custom name survive as they came.
+ let mut w = Writer::new();
+ w.bool(false);
+ w.bool(true);
+ w.i32(0x00FF_8800);
+ w.varint(1);
+ for v in [1, 1, 600] {
+ w.varint(v);
+ }
+ for b in [false, true, true, false] {
+ w.bool(b);
+ }
+ w.bool(true);
+ w.string("Tea");
+ let mut r = Reader::new(&w.data);
+ let read = Component::read(component::POTION_CONTENTS, &mut r).unwrap();
+ assert_eq!(r.remaining(), 0);
+ let Component::Potion {
+ potion,
+ color,
+ rest,
+ } = &read
+ else {
+ panic!("{read:?}");
+ };
+ assert_eq!((*potion, *color), (None, Some(0x00FF_8800)));
+ assert!(!rest.is_empty());
+ let mut again = Writer::new();
+ read.write(component::POTION_CONTENTS, &mut again);
+ assert_eq!(again.data, w.data);
+ }
+
#[test]
fn stacks_round_trip() {
round:: , Slot>(None);
diff --git a/crates/horizon-protocol/src/item/skip.rs b/crates/horizon-protocol/src/item/skip.rs
index 152d0f0f1..aa436cc31 100644
--- a/crates/horizon-protocol/src/item/skip.rs
+++ b/crates/horizon-protocol/src/item/skip.rs
@@ -87,7 +87,6 @@ pub(super) fn component(kind: i32, r: &mut Reader) -> Result<()> {
}
// BundleContents: templates.
52 => list(r, template),
- 53 => potion_contents(r),
// SuspiciousStewEffects: effect, duration.
55 => list(r, |r| {
varint(r)?;
@@ -410,10 +409,9 @@ fn kinetic_weapon(r: &mut Reader) -> Result<()> {
optional(r, sound)?;
optional(r, sound)
}
-/// PotionContents: potion, customColor, customEffects, customName.
-fn potion_contents(r: &mut Reader) -> Result<()> {
- optional(r, varint)?;
- optional(r, i32)?;
+/// PotionContents' customEffects and customName (`Component::read` reads
+/// the potion and colour before them).
+pub(super) fn potion_effects_and_name(r: &mut Reader) -> Result<()> {
list(r, mob_effect)?;
optional(r, string)
}
From 87b3c9aa38e5568733a2678d0332ad33e0e792e3 Mon Sep 17 00:00:00 2001
From: socksprox
Date: Sun, 25 Oct 2026 13:51:12 +0100
Subject: [PATCH 15/88] Drop the stale craft grid when a remote menu closes
The server's AbstractContainerMenu.removed gives the grid and the
carried stack back to the inventory and syncs those slots, but the
client kept its copies: a crafting table closed with items inside left
ghost stacks in the inventory's 2x2 grid that could not be picked up.
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
crates/horizon-client/src/game/remote.rs | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 5a71b13a8..d8148f77f 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -4783,6 +4783,11 @@ impl Game<'_> {
self.mount_menu_reset();
// The client's menu has no level access: what it holds is the server's.
self.station = None;
+ // AbstractContainerMenu.removed: the server gives the grid and the
+ // carried stack back to the inventory and syncs it; the copies here
+ // are stale the moment the window closes.
+ self.craft_grid.fill(None);
+ self.carried = None;
self.craft_size = 2;
if let Some(key) = self.container.take() {
// Server containers stay renderable but lose their copied slots.
From df626cf2f381ff11ff72a2e7d3793e7078291cca Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 14:15:28 +0100
Subject: [PATCH 16/88] A tool that changes a block ends the click on a
server's client
On a server's client (single player on the server thread, LAN guests), a
shovel making a path, an axe stripping, a hoe tilling or honeycomb waxing
did not end the right click: the client went on to the other hand, so an
off-hand torch was predicted as placed and its hand swung instead of the
tool's (#1289).
Vanilla's client runs `Item.useOn` itself: its SUCCESS swings that hand
and `Minecraft.startUseItem` returns before the off hand. The client now
does the same when its prediction of the tool's use succeeds.
Fixes #1289
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game/remote.rs | 17 ++++++++++++++---
1 file changed, 14 insertions(+), 3 deletions(-)
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index c1ef53122..8edfd77a2 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -4000,8 +4000,14 @@ impl Game<'_> {
}
if reacts {
self.predict_use(&changes, seq);
- } else if let Some(stack) = held.as_ref() {
- self.predict_item_on_block(stack, &hit);
+ } else if let Some(stack) = held.as_ref()
+ && self.predict_item_on_block(stack, &hit)
+ {
+ // Item.useOn succeeded here (InteractionResult.SUCCESS):
+ // this hand swings and the click ends, so the other hand
+ // (a shield, a torch) is never tried.
+ self.with_hand(hand, Game::swing_arm);
+ return true;
}
if held_block {
let placed = if reacts {
@@ -4031,7 +4037,8 @@ impl Game<'_> {
/// `playSound(player, ...)`: the server sends them to the others only):
/// honeycomb waxing copper, and an axe, hoe or shovel transforming a
/// block (stripping, scraping, removing wax, tilling, making a path).
- fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) {
+ /// Whether the item's use succeeded, which ends the click.
+ fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) -> bool {
let at = [
f64::from(hit.pos[0]) + 0.5,
f64::from(hit.pos[1]) + 0.5,
@@ -4050,11 +4057,15 @@ impl Game<'_> {
self.audio
.play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0);
}
+ waxes
} else if let Some((_, sound, _, _, particle)) =
self.block_transform(stack, hit.pos, hit.face)
{
self.transform_particle(&particle, hit.pos);
self.audio.play(&sound, Some(at), 1.0, 1.0);
+ true
+ } else {
+ false
}
}
From fb1142cd71dba47247f5f897c8ff487362431413 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 14:31:41 +0100
Subject: [PATCH 17/88] Skins: keep vanilla's whole-payload rejection, drop the
dead name fallback
authlib 10.0.77 MinecraftServicesSessionService.unpackTextures returns
MinecraftProfileTextures.EMPTY when any texture has no URL or a URL outside
the allowed domains, so skins::unpack goes back to main's behaviour.
remote_player_names: r.players and r.tab_players are filled from the same
ADD_PLAYER entries and emptied by the same PlayerInfoRemove, so the
tab-list fallback could never apply.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game/remote.rs | 9 +--------
crates/horizon-client/src/hud.rs | 5 +++--
crates/horizon-client/src/skins.rs | 21 ++++++++++-----------
3 files changed, 14 insertions(+), 21 deletions(-)
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 36122d42a..74850110b 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -5068,14 +5068,7 @@ impl Game<'_> {
r.level_players
.iter()
.filter(|(_, uuid)| **uuid != r.profile)
- .filter_map(|(id, uuid)| {
- let name = r
- .players
- .get(uuid)
- .cloned()
- .or_else(|| r.tab_players.get(uuid).map(|t| t.name.clone()))?;
- Some((*id as u32, name))
- })
+ .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone())))
.collect()
}
/// `ClientClockManager.tick`: the clock moves on by the game time that
diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs
index 90a8b346c..617126c2e 100644
--- a/crates/horizon-client/src/hud.rs
+++ b/crates/horizon-client/src/hud.rs
@@ -78,8 +78,9 @@ pub const MAP_SLOTS: usize = 256;
/// The atlas slot the minimap extra draws into.
pub const MINIMAP_SPRITE: &str = "horizon/minimap";
/// Atlas slots for downloaded player skins (`skins/`), 64x64 each.
-/// Vanilla registers a texture per skin; too few slots evict a busy
-/// server's players back to their default skins.
+/// Vanilla registers a texture per skin. Here a skin evicted from its slot
+/// is not stored again, and its player falls back to the default skin, so
+/// the slots must cover a busy server's player list.
pub const SKIN_SLOTS: usize = 128;
/// Reused by the visible rows of the classic world selector.
pub const WORLD_ICON_SLOTS: usize = 32;
diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs
index 0cf9cc8a2..9014032c4 100644
--- a/crates/horizon-client/src/skins.rs
+++ b/crates/horizon-client/src/skins.rs
@@ -92,23 +92,22 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture
..empty.clone()
};
for (kind, texture) in textures {
+ let Some(url) = texture.get("url").and_then(|u| u.as_str()) else {
+ return empty;
+ };
+ let allowed = valid_uris
+ .iter()
+ .any(|u| url.starts_with(&u.replace("{textureId}", "")));
+ if !allowed {
+ return empty;
+ }
let slot = match kind.as_str() {
"SKIN" => &mut out.skin,
"CAPE" => &mut out.cape,
"ELYTRA" => &mut out.elytra,
_ => continue,
};
- // One bad entry (no `url`, or a URL outside the texture services'
- // domains) drops only that texture, not the whole payload.
- let Some(url) = texture.get("url").and_then(|u| u.as_str()) else {
- continue;
- };
- let allowed = valid_uris
- .iter()
- .any(|u| url.starts_with(&u.replace("{textureId}", "")));
- if allowed {
- *slot = Some(url.to_owned());
- }
+ *slot = Some(url.to_owned());
}
out
}
From 2f1f0150eb112062fb696676bc578ba174fa3472 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 14:37:26 +0100
Subject: [PATCH 18/88] mobs diagnostics: say why passenger is set outside the
json! macro
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game/creatures.rs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index 5cfcefdb8..c4779dbf7 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -371,7 +371,9 @@ impl Game<'_> {
"vehicle": m.extra.mount,
})),
});
- state["passenger"] = serde_json::json!(m.extra.passenger);
+ // Drawn seated (Entity.isPassenger); set apart because the
+ // json! above is at the macro recursion limit.
+ state["passenger"] = m.extra.passenger.into();
state
})
.collect();
From 68deac8533c0a7072785712940b643f11c34c039 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 14:38:44 +0100
Subject: [PATCH 19/88] Server clients see mobs' aggression and arm swings
Mob.DATA_MOB_FLAGS_ID now carries the aggressive bit (with its default
0, so it goes back off) and every client mob reads no AI, left-handed
and aggressive from it: a vindicator draws its axe, skeletons their bow,
piglins and illagers their attack poses on the server thread, LAN guests
and dedicated servers. Mobs' swings (LivingEntity.swing) go out as
ClientboundSwingAnimationPacket.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game/lan.rs | 24 +++++++++++++++----
crates/horizon-client/src/game/remote.rs | 9 -------
.../src/game/remote_mob_data.rs | 21 ++++++++++++++++
3 files changed, 40 insertions(+), 14 deletions(-)
diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs
index 8460f54e6..97b4d2ba7 100644
--- a/crates/horizon-client/src/game/lan.rs
+++ b/crates/horizon-client/src/game/lan.rs
@@ -55,8 +55,8 @@ pub(super) struct LanHost {
pub play: HashMap,
/// Blocks broken this tick (their sound is a level event for the guests).
pub broken: Vec<[f64; 3]>,
- /// Hurt and death state of the mobs guests see.
- mob_state: HashMap>,
+ /// Hurt time, death and swing time (while swinging) of the mobs guests see.
+ mob_state: HashMap)>>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap,
/// An integrated server's owner (game/integrated.rs).
@@ -168,11 +168,15 @@ fn mob_meta(
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
defaults.push((9, serializer::FLOAT, Value::Float(1.0)));
- // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2.
- let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1;
+ // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what
+ // draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised
+ // weapon).
+ let flags =
+ i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1 | i8::from(m.ai.aggressive) << 2;
if flags != 0 {
meta.push((15, serializer::BYTE, Value::Byte(flags)));
}
+ defaults.push((15, serializer::BYTE, Value::Byte(0)));
// AgeableMob.DATA_BABY_ID (and Zombie's, Piglin's).
if let Some(index) = baby_index(kind) {
if m.is_baby() {
@@ -1193,7 +1197,17 @@ impl Game<'_> {
if dead && !old.is_some_and(|o| o.1) {
host.hub.entity_event(m.id as i32, 3, at);
}
- seen.insert(m.id, (m.hurt_time, dead));
+ // LivingEntity.swing on a server (a melee hit, a thrown potion):
+ // ClientboundSwingAnimationPacket for the players around. A swing
+ // started since the last flush, or restarted (its time went back).
+ let swing = m.ai.swinging.then_some(m.ai.swing_time);
+ if let Some(time) = swing
+ && !dead
+ && old.and_then(|o| o.2).is_none_or(|before| time < before)
+ {
+ host.hub.swing(m.id as i32, 0, at, None);
+ }
+ seen.insert(m.id, (m.hurt_time, dead, swing));
}
host.mob_state.insert(self.dim, seen);
}
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 044e43835..11d2b367c 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -1994,15 +1994,6 @@ impl Game<'_> {
}
}
}
- if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
- && m.species() == horizon_client::mobs::Species::Rabbit
- {
- for (index, _, value) in &p.values {
- if let (15, Value::Byte(flags)) = (index, value) {
- m.no_ai = flags & 1 != 0;
- }
- }
- }
self.remote_mob_data(p.id, &p.values);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Creeper
diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs
index 5573d0f87..64c092142 100644
--- a/crates/horizon-client/src/game/remote_mob_data.rs
+++ b/crates/horizon-client/src/game/remote_mob_data.rs
@@ -23,6 +23,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
// LivingEntity.DATA_HEALTH_ID: the boss bars and the death
// animation follow it.
(9, Value::Float(health)) => m.health = *health,
+ // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4.
+ // Mob.isAggressive draws the illagers' and skeletons' attack
+ // poses and the vindicator's axe.
+ (15, Value::Byte(flags)) => {
+ m.no_ai = flags & 1 != 0;
+ m.extra.left_handed = flags & 2 != 0;
+ m.ai.aggressive = flags & 4 != 0;
+ }
(i, Value::Bool(b)) if Some(i) == baby => m.extra.age = if *b { -1 } else { 0 },
_ => {}
}
@@ -178,6 +186,19 @@ mod tests {
assert_eq!(m.fire_ticks, 0);
}
+ #[test]
+ fn mob_flags_turn_aggression_on_and_off() {
+ let Some(mut m) = mob("minecraft:vindicator") else {
+ return;
+ };
+ apply(&mut m, &[(15, s::BYTE, Value::Byte(4 | 2))]);
+ assert!(m.ai.aggressive && m.extra.left_handed && !m.no_ai);
+ assert!(horizon_client::mobs::illager::shows_item(&m));
+ apply(&mut m, &[(15, s::BYTE, Value::Byte(0))]);
+ assert!(!m.ai.aggressive && !m.extra.left_handed);
+ assert!(!horizon_client::mobs::illager::shows_item(&m));
+ }
+
#[test]
fn a_villager_takes_its_type_profession_and_level() {
let Some(mut m) = mob("minecraft:villager") else {
From f56785c2f512eef6eff83687455cbee97ecbcd11 Mon Sep 17 00:00:00 2001
From: Kacpherek
Date: Sun, 25 Oct 2026 13:16:16 +0100
Subject: [PATCH 20/88] Keep a chunk's scheduled ticks when it unloads before
the next tick
attach_save_data took a chunk's ticks only from the tick scheduler, which
registers new chunks once a tick. A chunk loaded and unloaded again in
between was saved with its block and fluid ticks cleared, though its own
saved list still held them.
---
crates/horizon-client/src/game/persist.rs | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs
index d3afbf6ce..45ef8801f 100644
--- a/crates/horizon-client/src/game/persist.rs
+++ b/crates/horizon-client/src/game/persist.rs
@@ -76,15 +76,14 @@ impl Game<'_> {
let pos = ChunkPos::new(chunk.x, chunk.z);
let time = self.world.game_time;
let mut extras: ChunkExtras = chunk.saved.as_deref().cloned().unwrap_or_default();
+ // A chunk the scheduler hasn't registered yet (one loaded and
+ // unloaded again before the next tick) still holds its saved ticks:
+ // `register_chunk_ticks` empties that list once it takes them.
if let Some(t) = self.block_ticks.blocks.chunk(pos) {
extras.block_ticks = t.pack(time);
- } else {
- extras.block_ticks.clear();
}
if let Some(t) = self.block_ticks.fluids.chunk(pos) {
extras.fluid_ticks = t.pack(time);
- } else {
- extras.fluid_ticks.clear();
}
extras.last_update = time;
// TheEndGatewayBlockEntity saves its Age (the server copy's).
From e181b17e17a88f6c39fbb16dd4b81440d8e738e1 Mon Sep 17 00:00:00 2001
From: Kacpherek
Date: Sun, 25 Oct 2026 13:16:16 +0100
Subject: [PATCH 21/88] Register new chunks' ticks before post-processing them
postprocess_chunks ran before tick_blocks registered the chunks that
arrived since the last tick, so the fluid and block ticks their marks
schedule went to chunks the scheduler did not know and were dropped.
Vanilla registers a chunk's tick containers before postProcessGeneration.
---
crates/horizon-client/src/game/postprocess.rs | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/crates/horizon-client/src/game/postprocess.rs b/crates/horizon-client/src/game/postprocess.rs
index e896a77ab..77cba6832 100644
--- a/crates/horizon-client/src/game/postprocess.rs
+++ b/crates/horizon-client/src/game/postprocess.rs
@@ -27,6 +27,11 @@ impl Game<'_> {
if ready.is_empty() {
return Ok(());
}
+ // The ticks the marks schedule go to the chunks' containers, which a
+ // chunk that arrived since the last tick doesn't have yet
+ // (`LevelChunk.registerTickContainerInLevel` comes before
+ // `postProcessGeneration`).
+ self.sync_tick_chunks();
for key in ready {
let Some(chunk) = self.world.chunks.get_mut(&key) else {
continue;
From dbafda06ed699a4e6e2653abd2aaa620fcfb1859 Mon Sep 17 00:00:00 2001
From: Kacpherek
Date: Sun, 25 Oct 2026 13:38:10 +0100
Subject: [PATCH 22/88] Surface: specialise the material rule per gradient band
and surface side
Each chunk's compiled rule is specialised once for every band of y that
its vertical gradients bound, and for blocks below and at or above the
preliminary surface when the rule asks for it. Conditions those facts
decide are folded away, so a deep stone block evaluates only the rules
that can apply there (ore veins, the underground rules) instead of
walking the whole surface tree. Conditions only read the position and
the world, so the blocks are the same.
Surface stage, one thread, seed 1234: 2.45 -> 2.08 ms per chunk.
---
.../src/worldgen/material_condition.rs | 75 +++++++++
.../src/worldgen/material_condition/rule.rs | 159 +++++++++++++++++-
.../src/worldgen/material_stage.rs | 13 +-
3 files changed, 244 insertions(+), 3 deletions(-)
diff --git a/crates/horizon-world/src/worldgen/material_condition.rs b/crates/horizon-world/src/worldgen/material_condition.rs
index 6433b09a4..d0b6c4290 100644
--- a/crates/horizon-world/src/worldgen/material_condition.rs
+++ b/crates/horizon-world/src/worldgen/material_condition.rs
@@ -23,6 +23,7 @@ use horizon_core::{
pub use library::MaterialRuleLibrary;
pub use noise::MaterialNoiseSources;
use rule::CompiledRule;
+pub use rule::SurfaceVariants;
pub use rule::{MaterialRule, MaterialRuleError};
use std::{
collections::{BTreeMap, BTreeSet},
@@ -299,7 +300,81 @@ enum Kind {
},
Not(Box>),
}
+/// What a specialised rule may assume about every position it is applied to
+/// (`CompiledRule::specialize`): its y lies in `low..=high`, and whether it is
+/// at or above the column's preliminary surface level, when known.
+#[derive(Clone, Copy, Debug)]
+pub struct Facts {
+ pub low: i32,
+ pub high: i32,
+ pub above_surface: Option,
+}
+impl Clone for Kind
+where
+ R::Positional: Clone,
+{
+ fn clone(&self) -> Self {
+ match self {
+ Self::Simple(condition) => Self::Simple(condition.clone()),
+ Self::Biome(names) => Self::Biome(names.clone()),
+ Self::Constant(value) => Self::Constant(*value),
+ Self::Noise { sampler, min, max } => Self::Noise {
+ sampler: *sampler,
+ min: *min,
+ max: *max,
+ },
+ Self::Gradient { low, high, random } => Self::Gradient {
+ low: *low,
+ high: *high,
+ random: random.clone(),
+ },
+ Self::Not(child) => Self::Not(child.clone()),
+ }
+ }
+}
+impl Clone for Compiled
+where
+ R::Positional: Clone,
+{
+ fn clone(&self) -> Self {
+ Self {
+ kind: self.kind.clone(),
+ revision: self.revision,
+ result: self.result,
+ }
+ }
+}
impl Compiled {
+ /// The value `facts` decide for this condition at every position they
+ /// cover. Conditions read the position and the world, never change them,
+ /// so one decided in advance gives what testing it would.
+ fn decided(&self, facts: Facts) -> Option {
+ match &self.kind {
+ Kind::Constant(value) => Some(*value),
+ Kind::Simple(MaterialCondition::AbovePreliminarySurface) => facts.above_surface,
+ Kind::Gradient { low, high, .. } => {
+ if facts.high <= *low {
+ Some(true)
+ } else if facts.low >= *high {
+ Some(false)
+ } else {
+ None
+ }
+ }
+ Kind::Not(child) => child.decided(facts).map(|value| !value),
+ _ => None,
+ }
+ }
+ /// The vertical gradients' bounds, and whether the preliminary surface
+ /// is asked for.
+ fn inputs(&self, gradients: &mut Vec<(i32, i32)>, surface: &mut bool) {
+ match &self.kind {
+ Kind::Gradient { low, high, .. } => gradients.push((*low, *high)),
+ Kind::Simple(MaterialCondition::AbovePreliminarySurface) => *surface = true,
+ Kind::Not(child) => child.inputs(gradients, surface),
+ _ => {}
+ }
+ }
fn constant_result(&self) -> Option {
match &self.kind {
Kind::Constant(value) => Some(*value),
diff --git a/crates/horizon-world/src/worldgen/material_condition/rule.rs b/crates/horizon-world/src/worldgen/material_condition/rule.rs
index cf4fc8547..f3c2ae60d 100644
--- a/crates/horizon-world/src/worldgen/material_condition/rule.rs
+++ b/crates/horizon-world/src/worldgen/material_condition/rule.rs
@@ -1,5 +1,7 @@
//! Compiled material rule composition, sharing the condition worker's context.
-use super::{Compiled, Context, MaterialCondition, MaterialConditions, MaterialSurfaceQueries};
+use super::{
+ Compiled, Context, Facts, MaterialCondition, MaterialConditions, MaterialSurfaceQueries,
+};
use crate::{registry::BlockStateId, worldgen::DecodeError};
use horizon_core::{
density::DensitySampler,
@@ -209,6 +211,161 @@ impl CompiledRule {
}
}
}
+impl CompiledRule
+where
+ R::Positional: Clone,
+{
+ /// This rule where `facts` hold: conditions they decide are folded away,
+ /// with what can no longer produce a block, and a sequence stops at its
+ /// first child that always produces one. For every position the facts
+ /// cover it gives the block the whole rule gives.
+ fn specialize(&self, facts: Facts) -> Self {
+ match self {
+ Self::Empty => Self::Empty,
+ Self::Block(block) => Self::Block(*block),
+ Self::Bandlands => Self::Bandlands,
+ Self::OreVein {
+ blocks,
+ raw_ore_chance,
+ densities,
+ random,
+ } => Self::OreVein {
+ blocks: *blocks,
+ raw_ore_chance: *raw_ore_chance,
+ densities: *densities,
+ random: random.clone(),
+ },
+ Self::Condition { condition, rule } => match condition.decided(facts) {
+ Some(false) => Self::Empty,
+ Some(true) => rule.specialize(facts),
+ None => match rule.specialize(facts) {
+ Self::Empty => Self::Empty,
+ rule => Self::Condition {
+ condition: condition.clone(),
+ rule: Box::new(rule),
+ },
+ },
+ },
+ Self::Sequence(children) => {
+ let mut result = Vec::new();
+ for child in children {
+ let child = child.specialize(facts);
+ if matches!(child, Self::Empty) {
+ continue;
+ }
+ let last = child.always_produces();
+ result.push(child);
+ if last {
+ break;
+ }
+ }
+ match result.len() {
+ 0 => Self::Empty,
+ 1 => result.pop().unwrap(),
+ _ => Self::Sequence(result),
+ }
+ }
+ }
+ }
+ /// Whether applying this rule never gives `None` (only an error).
+ fn always_produces(&self) -> bool {
+ match self {
+ Self::Block(_) | Self::Bandlands => true,
+ Self::Sequence(children) => children.iter().any(Self::always_produces),
+ Self::Empty | Self::OreVein { .. } | Self::Condition { .. } => false,
+ }
+ }
+ fn inputs(&self, gradients: &mut Vec<(i32, i32)>, surface: &mut bool) {
+ match self {
+ Self::Condition { condition, rule } => {
+ condition.inputs(gradients, surface);
+ rule.inputs(gradients, surface);
+ }
+ Self::Sequence(children) => {
+ for child in children {
+ child.inputs(gradients, surface);
+ }
+ }
+ _ => {}
+ }
+ }
+}
+/// A rule specialised (`CompiledRule::specialize`) for each band of y between
+/// its vertical gradients' bounds, and below and at or above the preliminary
+/// surface when the rule asks for it: most blocks of a column, deep stone,
+/// then evaluate only the few rules that can apply there.
+pub struct SurfaceVariants {
+ /// The first y of each band after the first, ascending.
+ starts: Vec,
+ /// The rule index per band (two per band, below then above the surface,
+ /// when `surface`).
+ rules: Vec,
+ pub surface: bool,
+}
+impl SurfaceVariants {
+ /// The rule for a block at `y`, `above` the preliminary surface (ignored
+ /// unless `surface`).
+ #[inline]
+ pub fn rule(&self, y: i32, above: bool) -> usize {
+ let band = self.starts.partition_point(|&start| start <= y);
+ if self.surface {
+ self.rules[band * 2 + usize::from(above)]
+ } else {
+ self.rules[band]
+ }
+ }
+}
+impl MaterialConditions
+where
+ R::Positional: Clone,
+{
+ /// Add the specialised variants of rule `index` (`SurfaceVariants`).
+ pub fn surface_variants(&mut self, index: usize) -> Result {
+ let rule = self
+ .rules
+ .get(index)
+ .ok_or(MaterialRuleError::UnknownRule)?;
+ let (mut gradients, mut surface) = (Vec::new(), false);
+ rule.inputs(&mut gradients, &mut surface);
+ // A gradient is true at and below `low`, random between, false at
+ // and above `high`: it is decided within each band these bound.
+ let mut starts: Vec = gradients
+ .iter()
+ .flat_map(|&(low, high)| [low.saturating_add(1), high])
+ .collect();
+ starts.sort_unstable();
+ starts.dedup();
+ let mut variants = Vec::new();
+ for band in 0..=starts.len() {
+ let low = if band == 0 {
+ i32::MIN
+ } else {
+ starts[band - 1]
+ };
+ let high = starts.get(band).map_or(i32::MAX, |&next| next - 1);
+ let sides: &[Option] = if surface {
+ &[Some(false), Some(true)]
+ } else {
+ &[None]
+ };
+ for &above_surface in sides {
+ let facts = Facts {
+ low,
+ high,
+ above_surface,
+ };
+ variants.push(self.rules[index].specialize(facts));
+ }
+ }
+ let first = self.rules.len();
+ self.rules.extend(variants);
+ Ok(SurfaceVariants {
+ starts,
+ rules: (first..self.rules.len()).collect(),
+ surface,
+ })
+ }
+}
impl MaterialConditions {
/// Compile all children in order, even after an unconditional block rule.
/// Failed compilation never adds a partial rule to this worker.
diff --git a/crates/horizon-world/src/worldgen/material_stage.rs b/crates/horizon-world/src/worldgen/material_stage.rs
index 0763c4e63..fd51d3716 100644
--- a/crates/horizon-world/src/worldgen/material_stage.rs
+++ b/crates/horizon-world/src/worldgen/material_stage.rs
@@ -196,7 +196,10 @@ pub fn build_surface,
extensions: &MaterialExtensions,
-) -> Result<(), SurfaceError> {
+) -> Result<(), SurfaceError>
+where
+ R::Positional: Clone,
+{
let min = chunk.min_y();
let max = min + chunk.height() - 1;
if inputs.write_min_y < min
@@ -240,9 +243,13 @@ fn build_columns,
write_min_y: i32,
write_max_y: i32,
-) -> Result<(), SurfaceError> {
+) -> Result<(), SurfaceError>
+where
+ R::Positional: Clone,
+{
let min = chunk.min_y();
let rule = worker.add_rule(rule)?;
+ let variants = worker.surface_variants(rule)?;
let cx = chunk.position().x.wrapping_shl(4);
let cz = chunk.position().z.wrapping_shl(4);
for lx in 0..16 {
@@ -321,6 +328,8 @@ fn build_columns= write_min_y && y <= write_max_y {
+ let above = variants.surface && y >= worker.minimum_surface_level()?;
+ let rule = variants.rule(y, above);
if let Some(state) = worker.try_apply(rule, BlockPos::new(x, y, z))? {
column.set_block(y, state)?;
}
From 56560b467a8fad3ffe02457691bd8486a1a77cb6 Mon Sep 17 00:00:00 2001
From: socksprox
Date: Sun, 25 Oct 2026 00:19:47 +0200
Subject: [PATCH 23/88] Multiplayer: answer cookie requests, store cookies,
follow transfer packets
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
ClientboundCookieRequestPacket in play state decoded as Unknown and was
dropped; StoreCookie and Transfer likewise, and the configuration-phase
CookieRequest was always answered empty. Proxies (BungeeCord, Velocity)
store and read cookies around a server switch and send Transfer to move
a player to another address — both ended in a kick.
Play-state cookie_request/store_cookie/transfer now have packet types,
cookie requests answer from the stored cookies in both configuration and
play (ClientCommonPacketListenerImpl.handleRequestCookie), stored cookies
land in the session's map (handleStoreCookie), and a transfer reconnects
the game to the target address carrying them (handleTransfer →
ConnectScreen.startConnecting with TransferState).
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
crates/horizon-client/src/game.rs | 10 +-
crates/horizon-client/src/game/remote.rs | 51 +++++++++-
.../horizon-client/src/game/startup_menu.rs | 4 +-
crates/horizon-client/src/net.rs | 94 +++++++++++++++++--
crates/horizon-protocol/src/packets/play.rs | 9 +-
5 files changed, 153 insertions(+), 15 deletions(-)
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 699468651..7fcb3be89 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -12098,6 +12098,8 @@ enum PendingWorldEntry {
Server {
address: String,
name: String,
+ /// A transfer's carried-over server cookies (`TransferState`).
+ cookies: Option,
},
}
@@ -12172,8 +12174,12 @@ impl Game<'_> {
}) => {
self.open_world(&folder, name.as_deref(), seed, creative, create.as_deref())?;
}
- Some(PendingWorldEntry::Server { address, name }) => {
- self.connect_server(&address, &name)?;
+ Some(PendingWorldEntry::Server {
+ address,
+ name,
+ cookies,
+ }) => {
+ self.connect_server_with_cookies(&address, &name, cookies)?;
}
None => {}
}
diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs
index 044e43835..c10b64c54 100644
--- a/crates/horizon-client/src/game/remote.rs
+++ b/crates/horizon-client/src/game/remote.rs
@@ -193,6 +193,9 @@ pub(super) struct Remote {
/// the oldest of them first waited (`poll_remote`).
backlog: VecDeque,
backlog_since: Option,
+ /// `ClientboundTransferPacket`'s target: when the connection ends the
+ /// game connects here, the stored cookies carried over (`TransferState`).
+ transfer: Option,
}
/// The time a frame spends on chunk packets before it leaves the rest of
@@ -257,14 +260,25 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
impl Game<'_> {
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
+ self.connect_server_with_cookies(address, name, None)
+ }
+ /// `connect_server` carrying a transfer's stored server cookies
+ /// (`TransferState`); None on an ordinary join.
+ pub(super) fn connect_server_with_cookies(
+ &mut self,
+ address: &str,
+ name: &str,
+ cookies: Option,
+ ) -> Result<()> {
if self.defer_world_entry(super::PendingWorldEntry::Server {
address: address.to_owned(),
name: name.to_owned(),
+ cookies: cookies.clone(),
})? {
return Ok(());
}
self.join_world_rest()?;
- if let Err(error) = self.join_server(address, name, None) {
+ if let Err(error) = self.join_server(address, name, None, cookies) {
log::warn!("Horizon: could not join server: {error}");
if self.title.is_none() {
self.title = Some(horizon_client::title::Title::new(
@@ -285,13 +299,14 @@ impl Game<'_> {
pipe: horizon_protocol::connection::Pipe,
name: &str,
) -> Result<()> {
- self.join_server("local", name, Some(pipe))
+ self.join_server("local", name, Some(pipe), None)
}
fn join_server(
&mut self,
address: &str,
name: &str,
local: Option,
+ cookies: Option,
) -> Result<()> {
self.perf.world_opening();
let root = self.options.resources.clone();
@@ -323,7 +338,17 @@ impl Game<'_> {
Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()),
None => {
self.extras_connecting(address, name);
- Session::connect(address, name, auth.clone(), view, lang.clone())
+ match cookies {
+ Some(cookies) => Session::connect_transferred(
+ address,
+ name,
+ auth.clone(),
+ view,
+ lang.clone(),
+ cookies,
+ ),
+ None => Session::connect(address, name, auth.clone(), view, lang.clone()),
+ }
}
};
let player_type = super::perspective::player_type(&root);
@@ -446,6 +471,7 @@ impl Game<'_> {
chunk_center: (0, 0),
backlog: VecDeque::new(),
backlog_since: None,
+ transfer: None,
});
// The level's TickRateManager follows the server's ticking packets.
self.clock = horizon_client::clock::FixedStep::client();
@@ -867,6 +893,11 @@ impl Game<'_> {
}
}
Event::Reconfigured(registries) => self.set_registries(registries),
+ Event::Transfer { host, port } => {
+ if let Some(r) = self.remote.as_mut() {
+ r.transfer = Some(format!("{host}:{port}"));
+ }
+ }
Event::PackPush(p) => self.handle_pack_push(p),
Event::PackPop(id) => self.handle_pack_pop(id),
Event::DecodeError(e) => {
@@ -882,6 +913,20 @@ impl Game<'_> {
from_server,
} => {
log::info!("Horizon: disconnected: {reason}");
+ // ClientboundTransferPacket left a target: connect there
+ // instead of showing the disconnect, the stored cookies
+ // carried over (ClientCommonPacketListenerImpl.
+ // handleTransfer → ConnectScreen.startConnecting).
+ let transfer = self.remote.as_mut().and_then(|r| {
+ r.transfer.take().map(|address| {
+ (address, r.session.name.clone(), r.session.cookies.clone())
+ })
+ });
+ if let Some((address, name, cookies)) = transfer {
+ self.leave_server(None)?;
+ self.connect_server_with_cookies(&address, &name, Some(cookies))?;
+ return Ok(());
+ }
let retry = self.reconnect_after(&reason, from_server);
self.leave_server(Some(reason))?;
self.offer_reconnect(retry);
diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs
index 96af99bbc..fe568fe71 100644
--- a/crates/horizon-client/src/game/startup_menu.rs
+++ b/crates/horizon-client/src/game/startup_menu.rs
@@ -33,6 +33,7 @@ impl StartupMenu {
Some(PendingWorldEntry::Server {
address: address.clone(),
name: options.player_name(),
+ cookies: None,
})
} else {
options
@@ -125,6 +126,7 @@ impl StartupMenu {
Action::Connect { address } => PendingWorldEntry::Server {
address,
name: player_name,
+ cookies: None,
},
_ => return,
};
@@ -762,7 +764,7 @@ mod tests {
"Guest".into(),
);
assert!(
- matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name })
+ matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name, .. })
if address == "localhost:25565" && name == "Guest")
);
assert!(menu.pending.take().is_none(), "an entry is consumed once");
diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs
index 9cce9e1c6..c4e53cef4 100644
--- a/crates/horizon-client/src/net.rs
+++ b/crates/horizon-client/src/net.rs
@@ -18,6 +18,7 @@ use horizon_protocol::{
text::{Language, plain, translatable},
};
use std::{
+ collections::HashMap,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
@@ -27,6 +28,12 @@ use std::{
time::Duration,
};
+/// `CommonListenerCookie.serverCookies`: cookies the server asked the client
+/// to store (`ClientboundStoreCookiePacket`), answered to
+/// `ClientboundCookieRequestPacket`. A `transfer` carries them to the next
+/// connection (`TransferState`), so a proxy's backend switch keeps them.
+pub type Cookies = Arc>>>;
+
/// What the network thread reports to the game.
pub enum Event {
/// Progress text for the connecting screen.
@@ -48,6 +55,13 @@ pub enum Event {
PackPush(cfg::ResourcePackPush),
/// ClientboundResourcePackPopPacket: one pack, or every pack.
PackPop(Option),
+ /// `ClientboundTransferPacket`: the server sent us to another address.
+ /// The connection ends right after; the game reconnects there with the
+ /// stored cookies.
+ Transfer {
+ host: String,
+ port: i32,
+ },
/// The connection ended. `from_server`: the server gave the reason (or
/// the connection was refused for good), rather than the connection
/// failing (auto-reconnect retries only failures and shutdowns).
@@ -67,6 +81,8 @@ pub struct Session {
pub address: String,
pub name: String,
pub counters: Arc>>>,
+ /// The cookies this server stored on us (`ClientboundStoreCookiePacket`).
+ pub cookies: Cookies,
/// HORIZON_NET_DEBUG=1 logs every packet sent from the game thread.
debug: bool,
}
@@ -79,7 +95,27 @@ impl Session {
view_distance: i8,
lang: Arc,
) -> Self {
- Self::start(address, name, auth, view_distance, lang, None)
+ Self::start(address, name, auth, view_distance, lang, None, None)
+ }
+ /// `ConnectScreen.startConnecting` for a `transfer`: the cookies the
+ /// server stored carry to the new connection (`TransferState`).
+ pub fn connect_transferred(
+ address: &str,
+ name: &str,
+ auth: Option>,
+ view_distance: i8,
+ lang: Arc,
+ cookies: Cookies,
+ ) -> Self {
+ Self::start(
+ address,
+ name,
+ auth,
+ view_distance,
+ lang,
+ None,
+ Some(cookies),
+ )
}
/// Join an integrated server through memory (`Connection.connectToLocalServer`).
pub fn connect_local(
@@ -88,7 +124,7 @@ impl Session {
view_distance: i8,
lang: Arc,
) -> Self {
- Self::start("local", name, None, view_distance, lang, Some(pipe))
+ Self::start("local", name, None, view_distance, lang, Some(pipe), None)
}
fn start(
address: &str,
@@ -97,12 +133,15 @@ impl Session {
view_distance: i8,
lang: Arc,
local: Option,
+ cookies: Option,
) -> Self {
let (send, events) = channel();
let writer = Arc::new(Mutex::new(None));
let configuring = Arc::new(AtomicBool::new(true));
let counters = Arc::new(Mutex::new(None));
- let (thread_writer, thread_counters) = (writer.clone(), counters.clone());
+ let cookies = cookies.unwrap_or_default();
+ let (thread_writer, thread_counters, thread_cookies) =
+ (writer.clone(), counters.clone(), cookies.clone());
let thread_configuring = configuring.clone();
let (address_owned, name_owned) = (address.to_owned(), name.to_owned());
let thread = std::thread::Builder::new()
@@ -119,6 +158,7 @@ impl Session {
&thread_writer,
&thread_configuring,
&thread_counters,
+ &thread_cookies,
);
let from_server = result.is_ok();
let reason = result.unwrap_or_else(|e| e);
@@ -140,6 +180,7 @@ impl Session {
address: address.to_owned(),
name: name.to_owned(),
counters,
+ cookies,
debug,
}
}
@@ -291,6 +332,7 @@ fn run(
shared_writer: &Mutex>,
configuring: &AtomicBool,
shared_counters: &Mutex >>,
+ cookies: &Cookies,
) -> Result {
let (host, port, mut c) = if let Some(pipe) = local {
(address.to_owned(), 0, Connection::local(pipe))
@@ -419,13 +461,13 @@ fn run(
.map_err(e)?;
let (mut reader, writer) = c.split();
*shared_writer.lock().unwrap() = Some(writer);
- let registries = configure(&mut reader, shared_writer, configuring, lang, send)?;
+ let registries = configure(&mut reader, shared_writer, configuring, lang, send, cookies)?;
let _ = send.send(Event::Joined {
registries: Arc::new(registries),
uuid: profile.uuid,
name: profile.name,
});
- receive_play(&mut reader, shared_writer, configuring, lang, send)
+ receive_play(&mut reader, shared_writer, configuring, lang, send, cookies)
}
fn receive_play(
@@ -434,6 +476,7 @@ fn receive_play(
configuring: &AtomicBool,
lang: &Language,
send: &Sender,
+ cookies: &Cookies,
) -> Result {
loop {
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
@@ -469,9 +512,31 @@ fn receive_play(
let _ = w.send(&play::Serverbound::ConfigurationAcknowledged(Empty).encode());
configuring.store(true, Ordering::Relaxed);
}
- let registries = configure(reader, shared_writer, configuring, lang, send)?;
+ let registries =
+ configure(reader, shared_writer, configuring, lang, send, cookies)?;
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
}
+ // ClientCommonPacketListenerImpl.handleRequestCookie: the stored
+ // cookie (or none) goes straight back.
+ play::Clientbound::CookieRequest(q) => {
+ let payload = cookies.lock().unwrap().get(&q.key).cloned();
+ reply(play::Serverbound::CookieResponse(cfg::CookieResponse {
+ key: q.key,
+ payload,
+ }));
+ }
+ play::Clientbound::StoreCookie(p) => {
+ cookies.lock().unwrap().insert(p.key, p.payload);
+ }
+ // ClientCommonPacketListenerImpl.handleTransfer: the connection
+ // ends and the game connects to the other address.
+ play::Clientbound::Transfer(p) => {
+ let _ = send.send(Event::Transfer {
+ host: p.host,
+ port: p.port,
+ });
+ return Ok(tr(lang, "disconnect.transfer"));
+ }
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
play::Clientbound::CustomPayload(p) if p.channel == "minecraft:brand" => {
receive_brand(&p, send);
@@ -493,6 +558,7 @@ fn configure(
configuring: &AtomicBool,
lang: &Language,
send: &Sender,
+ cookies: &Cookies,
) -> Result {
let mut registries = Dynamic::default();
let reply = |p: cfg::Serverbound| -> Result<(), String> {
@@ -525,11 +591,22 @@ fn configure(
let _ = send.send(Event::PackPop(p.id));
}
cfg::Clientbound::CookieRequest(q) => {
+ let payload = cookies.lock().unwrap().get(&q.key).cloned();
reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse {
key: q.key,
- payload: None,
+ payload,
}))?
}
+ cfg::Clientbound::StoreCookie(p) => {
+ cookies.lock().unwrap().insert(p.key, p.payload);
+ }
+ cfg::Clientbound::Transfer(p) => {
+ let _ = send.send(Event::Transfer {
+ host: p.host,
+ port: p.port,
+ });
+ return Err(tr(lang, "disconnect.transfer"));
+ }
cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)),
cfg::Clientbound::FinishConfiguration(_) => {
let mut w = writer.lock().unwrap();
@@ -659,6 +736,7 @@ mod tests {
&AtomicBool::new(false),
&Language::new(),
&send,
+ &Cookies::default(),
)
});
let mut server = Connection::local(server);
@@ -708,6 +786,7 @@ mod tests {
address: "local".into(),
name: "Player".into(),
counters: Arc::new(Mutex::new(None)),
+ cookies: Cookies::default(),
debug: false,
};
let (thread_writer, thread_configuring) =
@@ -719,6 +798,7 @@ mod tests {
&thread_configuring,
&Language::new(),
&send,
+ &Cookies::default(),
)
});
let mut server = Connection::local(server);
diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs
index 26bb96316..67373cf4b 100644
--- a/crates/horizon-protocol/src/packets/play.rs
+++ b/crates/horizon-protocol/src/packets/play.rs
@@ -13,8 +13,9 @@ use crate::{
packets::{
Empty,
configuration::{
- ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop,
- ResourcePackPush, ResourcePackResponse, UpdateTags,
+ ClientInformation, CookieRequest, CookieResponse, CustomPayload, Disconnect, KeepAlive,
+ Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse, StoreCookie, Transfer,
+ UpdateTags,
},
login::Property,
},
@@ -1759,6 +1760,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT,
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT,
+ CookieRequest(CookieRequest) = COOKIE_REQUEST,
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
Disconnect(Disconnect) = DISCONNECT,
DisguisedChat(DisguisedChat) = DISGUISED_CHAT,
@@ -1836,6 +1838,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
SoundEntity(SoundEntity) = SOUND_ENTITY,
StopSound(StopSound) = STOP_SOUND,
StartConfiguration(Empty) = START_CONFIGURATION,
+ StoreCookie(StoreCookie) = STORE_COOKIE,
SwingAnimation(SwingAnimation) = SWING_ANIMATION,
SystemChat(SystemChat) = SYSTEM_CHAT,
TabList(TabList) = TAB_LIST,
@@ -1843,6 +1846,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
TeleportEntity(TeleportEntity) = TELEPORT_ENTITY,
TickingState(TickingState) = TICKING_STATE,
TickingStep(TickingStep) = TICKING_STEP,
+ Transfer(Transfer) = TRANSFER,
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES,
LevelParticles(LevelParticles) = LEVEL_PARTICLES,
@@ -2223,6 +2227,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK,
ContainerClick(ContainerClick) = CONTAINER_CLICK,
ContainerClose(ContainerClose) = CONTAINER_CLOSE,
+ CookieResponse(CookieResponse) = COOKIE_RESPONSE,
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
EditBook(EditBook) = EDIT_BOOK,
Interact(Interact) = INTERACT,
From a2fccf0205c133ef871bb9a781dddac1cce52a6c Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 14:52:17 +0100
Subject: [PATCH 24/88] Flint and steel lights nether portals only in the
Overworld and the Nether
BaseFireBlock.inPortalDimension: a frame lit in the End stays a fire.
The world code's fire placement already checked it; the flint-and-steel
path (Game::try_light_portal) didn't, so a portal could be lit and used
in the End in every mode.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game.rs | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 699468651..36926afde 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -7879,8 +7879,12 @@ impl Game<'_> {
(0..width).all(|i| frame([left[0] + d[0] * i, left[1] + height, left[2] + d[2] * i]));
((3..=21).contains(&height) && top_ok).then_some((left, width, height))
}
- /// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal.
+ /// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal,
+ /// only in the Overworld and the Nether (`inPortalDimension`).
fn try_light_portal(&mut self, at: [i32; 3]) -> Result {
+ if !matches!(self.dim, Dim::Overworld | Dim::Nether) {
+ return Ok(false);
+ }
for x_axis in [true, false] {
if let Some((origin, width, height)) = self.portal_shape(at, x_axis) {
let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] };
From 93d05591c26a9706bdecd8ab63918b8776aded21 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 15:04:04 +0100
Subject: [PATCH 25/88] horizon-mod-registry: a submission's pull request says
it came through the form
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The form opens pull requests with the registry's token, which is Ludovic's
account, so the body now starts "🤖 Submitted through playhorizon.dev by
@login" and says neither Ludovic nor a reviewer wrote it.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-mod-registry/src/lib.rs | 7 ++++++-
crates/horizon-mod-registry/tests/submit.rs | 6 +++++-
2 files changed, 11 insertions(+), 2 deletions(-)
diff --git a/crates/horizon-mod-registry/src/lib.rs b/crates/horizon-mod-registry/src/lib.rs
index 9799bace8..72970017a 100644
--- a/crates/horizon-mod-registry/src/lib.rs
+++ b/crates/horizon-mod-registry/src/lib.rs
@@ -625,11 +625,16 @@ pub fn publish(
.map(|r| format!("- needs {} {}", r.id, r.version))
.collect();
let body = format!(
- "\nSubmitted by @{login} through [the form]({public}/mods/submit).\n\n\
+ "\n🤖 Submitted through [{site}]({public}/mods/submit) by @{login}. The form opens the pull request with \
+ the registry's token: neither Ludovic nor a reviewer wrote it.\n\n\
| | |\n|---|---|\n| Project | `{id}` ({kind}, {new}) |\n| Version | {version} for {game} |\n| File | `{file}`, {size} bytes, SHA-256 `{sha256}` |\n| Signed | {signed} |\n| Source | {source} |\n\n{lists}\n\n\
The checks below run the file's own checks again and, for a mod, a trial run in the sandbox. \
Reviewers: read the source and the checks' report before you approve.",
public = config.public_url,
+ site = config
+ .public_url
+ .split_once("://")
+ .map_or(config.public_url.as_str(), |(_, host)| host),
id = form.id,
kind = kind.name(),
new = if is_new { "new" } else { "update" },
diff --git a/crates/horizon-mod-registry/tests/submit.rs b/crates/horizon-mod-registry/tests/submit.rs
index 77487089d..f586effac 100644
--- a/crates/horizon-mod-registry/tests/submit.rs
+++ b/crates/horizon-mod-registry/tests/submit.rs
@@ -303,7 +303,11 @@ async fn a_submission_becomes_a_pull_request() {
assert!(message.contains("Co-authored-by: alice <7+alice@users.noreply.github.com>"));
assert_eq!(replaced, &None);
let body = m.pulls[0]["body"].as_str().unwrap();
- assert!(body.starts_with(""), "{body}");
+ assert!(
+ body.starts_with("\n🤖 Submitted through "),
+ "{body}"
+ );
+ assert!(body.contains("/mods/submit) by @alice."), "{body}");
assert!(body.contains("may draw text on your screen"), "{body}");
}
// The same version again: its branch is there.
From e9d2c1041774e9e291c2b8e360bf5c7e2485ffb7 Mon Sep 17 00:00:00 2001
From: vlesmentie <129341611+vlesmentie@users.noreply.github.com>
Date: Sun, 25 Oct 2026 10:32:36 -0300
Subject: [PATCH 26/88] Peaceful zombie horses spawn without their zombie rider
ZombieHorse.finalizeSpawn gets its rider from EntityType.create, which
returns null for a notInPeaceful type (the zombie) in peaceful, so vanilla
spawns the zombie horse alone there. spawn_jockeys created the rider
regardless. mobs/finalize.rs already skips it through level.create.
Fixes #1761.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-client/src/game/passengers.rs | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
diff --git a/crates/horizon-client/src/game/passengers.rs b/crates/horizon-client/src/game/passengers.rs
index b20c1560b..8f205c484 100644
--- a/crates/horizon-client/src/game/passengers.rs
+++ b/crates/horizon-client/src/game/passengers.rs
@@ -147,8 +147,16 @@ impl Game<'_> {
}
}
Species::Strider if !baby => self.spawn_strider_jockey(id, at),
- // ZombieHorse.finalizeSpawn: a zombie with an iron spear.
- Species::ZombieHorse if natural => {
+ // ZombieHorse.finalizeSpawn: a zombie with an iron spear. The rider
+ // comes from EntityType.create, which makes no zombie in peaceful
+ // (canSpawn), so a peaceful zombie horse spawns without one.
+ Species::ZombieHorse
+ if natural
+ && (self.ui.difficulty != 0
+ || horizon_client::mobs::spawn_rules::allowed_in_peaceful(
+ Species::Zombie,
+ )) =>
+ {
if let Some(zombie) = self.spawn_mob("minecraft:zombie", at, false) {
if let Some(z) = self.mobs.iter_mut().find(|m| m.id == zombie) {
z.extra.main_hand = Some("minecraft:iron_spear".into());
From ceff5a2110bfcaf460898909f08e532f19f767e2 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 15:06:34 +0100
Subject: [PATCH 27/88] Launcher: installing a taken-down registry mod says it
was taken down, and why
It said the mod had no version for 26.3.
Co-Authored-By: Claude Opus 5.5
---
launcher/src/browser/horizon.rs | 17 +++++++++++++----
launcher/src/browser/horizon/tests.rs | 2 +-
2 files changed, 14 insertions(+), 5 deletions(-)
diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs
index 5333e481d..501295c6b 100644
--- a/launcher/src/browser/horizon.rs
+++ b/launcher/src/browser/horizon.rs
@@ -374,10 +374,19 @@ fn install_from(
/// A project's newest version for this game that wasn't taken down.
fn newest<'a>(index: &Index, p: &'a index::Project) -> Result<&'a index::Version, String> {
- p.versions
- .iter()
- .find(|v| v.game == GAME && index.revoked(&p.id, &v.file.sha256).is_none())
- .ok_or_else(|| format!("{} has no version for {GAME} to install.", p.name))
+ let mut taken_down = None;
+ for v in p.versions.iter().filter(|v| v.game == GAME) {
+ match index.revoked(&p.id, &v.file.sha256) {
+ None => return Ok(v),
+ Some(r) => {
+ taken_down.get_or_insert(r);
+ }
+ }
+ }
+ Err(match taken_down {
+ Some(r) => format!("{} was taken down: {}", p.name, r.reason),
+ None => format!("{} has no version for {GAME} to install.", p.name),
+ })
}
/// Installs version `v` of the registry's mod or resource pack `p` into the game folder `home`.
diff --git a/launcher/src/browser/horizon/tests.rs b/launcher/src/browser/horizon/tests.rs
index caff9cd99..bf98719d7 100644
--- a/launcher/src/browser/horizon/tests.rs
+++ b/launcher/src/browser/horizon/tests.rs
@@ -123,7 +123,7 @@ fn refuses_a_changed_file_a_taken_id_and_local_files_from_the_real_registry() {
date: String::new(),
});
let e = install_from(&taken_down, true, &p, &home, &|_, _| {}).unwrap_err();
- assert!(e.contains("no version"), "{e}");
+ assert_eq!(e, "Coordinates HUD was taken down: Test.");
fs::remove_dir_all(&home).unwrap();
}
From 22c3f2bd0f63d88f27e4badd82f8e613c36e9804 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 15:13:51 +0100
Subject: [PATCH 28/88] Roadmap: roadmap/roadmap.toml, ROADMAP.md generated
from it, and its checks
One source of truth for what is being done, what comes next and where to help: roadmap/roadmap.toml,
each item said twice (plain words for players, the technical picture for contributors), Now / Next /
Later / Help wanted / Shipped, no dates. tools/roadmap.py builds ROADMAP.md from it, checks its rules
offline (CI, through tests/test_roadmap.py) and against GitHub (links resolve, no stale Now item),
ships items whose pull requests all went out in a release (sync), and keeps a roadmap: label per
item (labels). README links it; roadmap/README.md is the maintenance guide.
Co-Authored-By: Claude Opus 5.5
---
README.md | 5 +
ROADMAP.md | 341 ++++++++++++++++++++++++++
roadmap/README.md | 56 +++++
roadmap/roadmap.toml | 477 ++++++++++++++++++++++++++++++++++++
tests/test_roadmap.py | 207 ++++++++++++++++
tools/pr_ready.py | 6 +-
tools/roadmap.py | 551 ++++++++++++++++++++++++++++++++++++++++++
7 files changed, 1641 insertions(+), 2 deletions(-)
create mode 100644 ROADMAP.md
create mode 100644 roadmap/README.md
create mode 100644 roadmap/roadmap.toml
create mode 100644 tests/test_roadmap.py
create mode 100644 tools/roadmap.py
diff --git a/README.md b/README.md
index 6dd192d5d..ceee29249 100644
--- a/README.md
+++ b/README.md
@@ -16,6 +16,7 @@
Download ·
Documentation ·
Release notes ·
+ Roadmap ·
Project status ·
Contributing
@@ -109,6 +110,10 @@ Everything prepared lands in the gitignored `.local/`. It is derived from the ga
The client starts on the title screen. Command-line options (`--world`, `--seed`, `--creative`, `--render-distance`, `--dedicated`), controls, scripting through `horizon-ctl` and the architecture are described in [the native client guide](docs/native-client.md). The rest of the developer documentation is indexed in [docs/README.md](docs/README.md), including [the parity workflow](docs/parity-workflow.md).
+## Roadmap
+
+What is being done now, what comes next and where you can help, in plain words and in technical detail: [ROADMAP.md](ROADMAP.md). [playhorizon.dev/hub](https://playhorizon.dev/hub) shows it with the work board, the journal of what shipped and how to help.
+
## Contributing
Issues and pull requests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md) for how we work (vanilla first, small pull requests, labels), or [the contributing guide](https://playhorizon.dev/docs/contributing) on the site. Questions and ideas: [Discord](https://discord.gg/HcTeMZxe5E). Before opening a pull request, run the self-check and paste the block it prints:
diff --git a/ROADMAP.md b/ROADMAP.md
new file mode 100644
index 000000000..b433fad3a
--- /dev/null
+++ b/ROADMAP.md
@@ -0,0 +1,341 @@
+# Horizon roadmap
+
+
+
+What is being done on Horizon, what comes next and where you can help. There are no dates: things are Now, Next or Later. Each item is said in plain words, with the technical picture folded under it. The same roadmap, with a Simple / Technical switch, the board, the journal and how to help, is on [playhorizon.dev/hub](https://playhorizon.dev/hub). Pull requests carry the `roadmap:` label of their item.
+
+## At a glance
+
+Horizon is Minecraft: Java Edition 26.3 rewritten from scratch in Rust, so it runs faster on the same computer. Single player, LAN, servers, resource packs and Horizon's own mods work today, on your own copy of the game.
+
+**Being done now**
+
+- **Steady frames at long render distances**: Making Horizon faster than vanilla on every computer, with smooth camera movement even at 32 chunks, by spreading the work better over the processor's cores.
+- **Modpacks' world generation, natively**: Making the world-generation mods of popular modpacks (new structures, YUNG's dungeons and mineshafts, packs built on Lithostitched) generate their worlds in Horizon, natively and fast.
+- **Playing on servers: everything shows as it should**: When you play on a server, other players, mobs, items and menus look and behave as in vanilla: skins, poses, item names, inventories and server networks.
+- **Single player as a server: the last differences**: Single player now runs a small server in the background, as vanilla does. We are fixing what still behaves differently there; every fix also works for LAN and server players.
+- **Horizon's mod registry**: One place for mods, modpacks and resource packs made for Horizon: browse them on the website and install them from the launcher in one click.
+
+**Next**: Microsoft sign-in (coming soon); CurseForge in the mod browser (coming soon); Fresh benchmarks against vanilla; Pistons push players and mobs; Horizon on Intel Macs.
+
+**How to help**: Play it and tell us what differs from vanilla (Discord or GitHub), run the benchmark on your computer, vote for what you want next, or pick one of the Help wanted items.
+
+**Developers**: Read CONTRIBUTING.md, pick a Help wanted item or a To do card, check vanilla's code for the behaviour, and paste the block `python3 tools/pr_ready.py` prints in your pull request.
+
+## Now
+
+### Performance
+
+#### Steady frames at long render distances
+
+Making Horizon faster than vanilla on every computer, with smooth camera movement even at 32 chunks, by spreading the work better over the processor's cores.
+
+Technical
+
+Frame pacing at render distance 32 ([#678](https://github.com/ludovic111/horizon/issues/678)): long frames come from work competing with the render thread. In review: world generation workers build free structure starts instead of queueing them ([#1760](https://github.com/ludovic111/horizon/issues/1760)), the worker pool leaves one core as vanilla does ([#1778](https://github.com/ludovic111/horizon/issues/1778)), and the terrain vertex arena is read as storage where flat draws run ([#1742](https://github.com/ludovic111/horizon/issues/1742)). Still open: far terrain at 48 to 64 chunks ([#718](https://github.com/ludovic111/horizon/issues/718)) and CPU-bound fields of block entities ([#717](https://github.com/ludovic111/horizon/issues/717)). Every change shows before and after numbers from `tools/perf_bench.py` against vanilla 26.3 ([docs/benchmark.md](docs/benchmark.md)).
+
+
+
+#### Faster block lookups
+
+Speeding up the code that reads and writes the blocks of the world, which almost everything in the game goes through: generation, lighting, meshing and ticking.
+
+Technical
+
+`PalettedContainer` and `PackedStorage` find an entry's word by multiply and shift instead of an integer division ([#1790](https://github.com/ludovic111/horizon/issues/1790), [#1794](https://github.com/ludovic111/horizon/issues/1794)); meshing looks up baked models by index, not by name ([#1747](https://github.com/ludovic111/horizon/issues/1747)). Each change keeps the paletted storage harnesses identical and shows its microbenchmark ([docs/performance/paletted-container-access-results.md](docs/performance/paletted-container-access-results.md)).
+
+
+
+### Modpacks
+
+#### Modpacks' world generation, natively
+
+Making the world-generation mods of popular modpacks (new structures, YUNG's dungeons and mineshafts, packs built on Lithostitched) generate their worlds in Horizon, natively and fast.
+
+Technical
+
+`horizon-port-pack` carries a pack's data-driven content over; structure mods that need code get a native port: YUNG's worldgen as written ([#1746](https://github.com/ludovic111/horizon/issues/1746)), Lithostitched's limited and guaranteed elements with pool and processor modifiers ([#1777](https://github.com/ludovic111/horizon/issues/1777)), its processors as the game's own types ([#1765](https://github.com/ludovic111/horizon/issues/1765)). Proved by the structure blocks and layout harnesses ([#1753](https://github.com/ludovic111/horizon/issues/1753), [#1757](https://github.com/ludovic111/horizon/issues/1757)). Mods whose Java code does more than world generation don't run ([docs/modpacks.md](docs/modpacks.md)).
+
+
+
+### Servers and multiplayer
+
+#### Playing on servers: everything shows as it should
+
+When you play on a server, other players, mobs, items and menus look and behave as in vanilla: skins, poses, item names, inventories and server networks.
+
+Technical
+
+Client-of-a-server fixes in `game/remote*.rs` and `horizon-protocol`: mobs' aggressive and item-use flags ([#1802](https://github.com/ludovic111/horizon/issues/1802), [#1798](https://github.com/ludovic111/horizon/issues/1798)), ghost items after a remote menu ([#1795](https://github.com/ludovic111/horizon/issues/1795)), skins ([#1652](https://github.com/ludovic111/horizon/issues/1652)), cookies and transfer packets for proxy networks ([#1650](https://github.com/ludovic111/horizon/issues/1650)), firework boosts ([#1671](https://github.com/ludovic111/horizon/issues/1671)), living-entity attributes and simulation distance ([#1731](https://github.com/ludovic111/horizon/issues/1731)), styled item names ([#1702](https://github.com/ludovic111/horizon/issues/1702)), primed TNT between updates ([#1710](https://github.com/ludovic111/horizon/issues/1710)).
+
+
+
+#### Server dialogs and login screens
+
+Servers that show dialogs, such as the register and login screens of AuthMe, will work in Horizon.
+
+Technical
+
+26.3's dialog packets and model ([#1720](https://github.com/ludovic111/horizon/issues/1720)), the dialog screen with its buttons and actions ([#1734](https://github.com/ludovic111/horizon/issues/1734)), then text and boolean inputs ([#1735](https://github.com/ludovic111/horizon/issues/1735)).
+
+
+
+### Mods and API
+
+#### Horizon's mod registry
+
+One place for mods, modpacks and resource packs made for Horizon: browse them on the website and install them from the launcher in one click.
+
+Technical
+
+Merged: the registry index (schema 1, `.hpack`, checks before install, [#1634](https://github.com/ludovic111/horizon/issues/1634)), `cargo horizon-mod check` ([#1642](https://github.com/ludovic111/horizon/issues/1642)) and the submission service (`crates/horizon-mod-registry`, [#1659](https://github.com/ludovic111/horizon/issues/1659)). In review: the website's /mods ([#1596](https://github.com/ludovic111/horizon/issues/1596)) and /mods/submit ([#1635](https://github.com/ludovic111/horizon/issues/1635)), and in the launcher the registry as a source ([#1636](https://github.com/ludovic111/horizon/issues/1636)), install, enable and takedowns ([#1637](https://github.com/ludovic111/horizon/issues/1637)), the Mods page ([#1638](https://github.com/ludovic111/horizon/issues/1638)) and modpacks as their own profiles ([#1640](https://github.com/ludovic111/horizon/issues/1640)).
+
+More: [docs/mods.md](docs/mods.md)
+
+
+
+### Gameplay parity
+
+#### Single player as a server: the last differences
+
+Single player now runs a small server in the background, as vanilla does. We are fixing what still behaves differently there; every fix also works for LAN and server players.
+
+Technical
+
+Since [#1514](https://github.com/ludovic111/horizon/issues/1514) single player runs on the server thread (`game/integrated.rs`) and the window joins it as a client; `--in-frame` keeps the old path. The open `[server-thread]` issues list the gaps. In review: a tool that changes a block ends the click ([#1797](https://github.com/ludovic111/horizon/issues/1797)), potions keep their potion over the connection ([#1796](https://github.com/ludovic111/horizon/issues/1796)), mobs' aggression and arm swings ([#1802](https://github.com/ludovic111/horizon/issues/1802)). [docs/server-levels.md](docs/server-levels.md).
+
+
+
+#### Play in your language
+
+Item names, container titles and server messages follow the language you pick, as in vanilla. Today parts of the game stay in English.
+
+Technical
+
+Translatable components resolved through the selected language for items, containers and server text ([#1806](https://github.com/ludovic111/horizon/issues/1806)), on top of the bundled languages the prepared resources carry ([#1594](https://github.com/ludovic111/horizon/issues/1594)). Left: the client's own screens ([#1672](https://github.com/ludovic111/horizon/issues/1672)) and the main menu with zh_cn ([#1774](https://github.com/ludovic111/horizon/issues/1774)).
+
+
+
+### Rendering
+
+#### Shader packs, written again from scratch
+
+Shader packs were removed and are being rebuilt from scratch. They come back, off by default, once the best-known packs draw properly.
+
+Technical
+
+A clean-room rewrite in `horizon-shaderpack`, from the packs' public format documentation only: reading packs, the preprocessor and `.properties` files are merged ([#1584](https://github.com/ludovic111/horizon/issues/1584), [#1585](https://github.com/ludovic111/horizon/issues/1585), [#1586](https://github.com/ludovic111/horizon/issues/1586)); translating programs to WGSL through naga, buffers, uniforms and the terrain, entity, sky, weather and hand stages are in review ([#1698](https://github.com/ludovic111/horizon/issues/1698) to [#1801](https://github.com/ludovic111/horizon/issues/1801)).
+
+More: [#1561](https://github.com/ludovic111/horizon/issues/1561) · [#1771](https://github.com/ludovic111/horizon/issues/1771) · [#1786](https://github.com/ludovic111/horizon/issues/1786)
+
+
+
+### Horizon extras
+
+#### Discord Rich Presence
+
+Your Discord profile can show that you are playing Horizon, with a switch to turn it off.
+
+Technical
+
+A Discord IPC client on its own thread ([#1787](https://github.com/ludovic111/horizon/issues/1787)) and the presence with its setting ([#1788](https://github.com/ludovic111/horizon/issues/1788)). Merged: it ships with the next release.
+
+
+
+### Code and tools
+
+#### A leaner codebase that builds faster
+
+Cleaning up Horizon's code: removing what nothing uses and making it quicker to build, so fixes and new features land faster.
+
+Technical
+
+A review of the whole tree: dead code and stubs removed ([#1432](https://github.com/ludovic111/horizon/issues/1432), [#1658](https://github.com/ludovic111/horizon/issues/1658)), one probe binary per crate ([#1453](https://github.com/ludovic111/horizon/issues/1453), [#1454](https://github.com/ludovic111/horizon/issues/1454)), shared harness helpers ([#1448](https://github.com/ludovic111/horizon/issues/1448)), clippy clean on the whole tree ([#1707](https://github.com/ludovic111/horizon/issues/1707)). [docs/architecture.md](docs/architecture.md) maps each feature to its files and harnesses.
+
+
+
+## Next
+
+### Performance
+
+#### Fresh benchmarks against vanilla
+
+New public numbers comparing Horizon with vanilla on many kinds of computers, measured the same way every time, on the website's Benchmarks page.
+
+Technical
+
+Redo the comparison after the current performance work ([#1073](https://github.com/ludovic111/horizon/issues/1073)); reliability, coverage and presentation ([#1346](https://github.com/ludovic111/horizon/issues/1346)); a scene must count as loaded only once its first chunk arrives ([#1749](https://github.com/ludovic111/horizon/issues/1749)). Players' reports come in through `--benchmark` and `horizon-launcher data benchmark` ([docs/benchmark.md](docs/benchmark.md)).
+
+
+
+### Modpacks
+
+#### CurseForge in the mod browser (coming soon)
+
+Coming soon: search and download CurseForge mods and modpacks from the launcher, as you can with Modrinth today.
+
+Technical
+
+The mod browser lists CurseForge as coming soon ([docs/mod-browser.md](docs/mod-browser.md)): it needs CurseForge API access. Meanwhile packs import from a CurseForge zip or instance folder, and jars only CurseForge hosts come from the player's own instance ([docs/modpacks.md](docs/modpacks.md)).
+
+
+
+### Gameplay parity
+
+#### Pistons push players and mobs
+
+Pistons and slime blocks will push players, mobs and items as in vanilla. Today moving blocks pass through them.
+
+Technical
+
+Port `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` (honey), the slime bounce and `Entity.limitPistonMovement` for `MoverType.PISTON`, in single player and for a server's players. Issues [#1496](https://github.com/ludovic111/horizon/issues/1496), [#1609](https://github.com/ludovic111/horizon/issues/1609), [#1608](https://github.com/ludovic111/horizon/issues/1608), [#1704](https://github.com/ludovic111/horizon/issues/1704), [#1758](https://github.com/ludovic111/horizon/issues/1758).
+
+
+
+### Launcher
+
+#### Microsoft sign-in (coming soon)
+
+Coming soon: sign in with your Microsoft account to play on online-mode servers. The code is ready; it waits for Microsoft's approval.
+
+Technical
+
+Device-code sign-in in the launcher and online-mode login in the client ([docs/microsoft-account.md](docs/microsoft-account.md)). It is turned on by setting the app's client id once Minecraft API access is approved; until then the launcher shows "Coming soon".
+
+More: [#1270](https://github.com/ludovic111/horizon/issues/1270)
+
+
+
+#### Horizon on Intel Macs
+
+Builds of the game and the launcher for Macs with an Intel processor.
+
+Technical
+
+x86_64 game and launcher builds, picked per processor ([#1171](https://github.com/ludovic111/horizon/issues/1171)). Before it ships it needs a run on a real Intel Mac: Rosetta on Apple Silicon only proves the CPU code. Requests: [#1161](https://github.com/ludovic111/horizon/issues/1161), [#1792](https://github.com/ludovic111/horizon/issues/1792).
+
+
+
+## Later
+
+### Gameplay parity
+
+#### Following new Minecraft versions
+
+When Mojang releases a new version of the game, Horizon follows it, and every system is checked against the new version again.
+
+Technical
+
+The port pipeline detects a release, diffs its classes against 26.3 and writes a port report ([docs/version-ports.md](docs/version-ports.md)); the harnesses then run against the new version.
+
+
+
+### Horizon extras
+
+#### An optional AI teammate
+
+An AI teammate that plays beside you and that you can talk to. It is off unless you turn it on, and the No AI switch hides it completely.
+
+Technical
+
+Draft pull requests: the companion ([#1068](https://github.com/ludovic111/horizon/issues/1068)), its safety modes and their evaluation ([#1069](https://github.com/ludovic111/horizon/issues/1069)), and a route that finishes the game ([#1070](https://github.com/ludovic111/horizon/issues/1070)). Local models first; it ships only once the safety evaluation passes.
+
+
+
+## Help wanted
+
+### Performance
+
+#### Benchmark your computer
+
+Run Horizon's built-in benchmark and share the report: every new computer makes the performance work more accurate. No coding needed.
+
+Technical
+
+`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it ([website/docs/performance.md](website/docs/performance.md)). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
+
+
+
+### Gameplay parity
+
+#### End city banners keep their pattern
+
+Banners in End cities show as plain magenta instead of with their pattern.
+
+Technical
+
+Compare the banner block entities the End city templates place with vanilla's (`EndCityPieces`, the templates' block entity NBT, `BannerBlockEntity`'s patterns), in `crates/horizon-world/src/worldgen/structure/`. Issue [#1438](https://github.com/ludovic111/horizon/issues/1438); possibly related: [#526](https://github.com/ludovic111/horizon/issues/526).
+
+
+
+#### Enchanted loot in End cities
+
+Armour and tools in End city chests should come enchanted, as in vanilla.
+
+Technical
+
+`loot.rs` implements `enchant_with_levels`: find why the End city chest table's rolls come out bare, and compare them with vanilla's for a few seeds. Issues [#1437](https://github.com/ludovic111/horizon/issues/1437), [#1660](https://github.com/ludovic111/horizon/issues/1660).
+
+
+
+#### Cooldowns drawn on items
+
+After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
+
+Technical
+
+Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
+
+
+
+#### Chat settings and team prefixes
+
+The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
+
+Technical
+
+Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
+
+
+
+#### A pointing hand over buttons
+
+The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
+
+Technical
+
+26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
+
+
+
+#### Ctrl+Backspace and scroll bars in menus
+
+Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
+
+Technical
+
+`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
+
+
+
+#### Chickens flap while they fall
+
+Chickens should flap their wings while they fall, not stand still in the air.
+
+Technical
+
+Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
+
+
+
+## Recently shipped
+
+- **Server resource packs** (v0.2.48): Servers can send you their resource pack: Horizon asks, downloads it and applies it, like vanilla. [#1562](https://github.com/ludovic111/horizon/issues/1562) · [#1569](https://github.com/ludovic111/horizon/issues/1569) · [#1570](https://github.com/ludovic111/horizon/issues/1570)
+- **Single player on its own server thread** (v0.2.39): Single player runs on a server thread, as vanilla does, so the world keeps ticking smoothly while the window draws. [#1514](https://github.com/ludovic111/horizon/issues/1514) · [docs/server-levels.md](docs/server-levels.md)
+- **GPU occlusion culling on Macs** (v0.2.17): On Macs the GPU now skips terrain hidden behind hills and caves: 8 to 48% more frames per second at 32 chunks on an M4 Pro. [#1434](https://github.com/ludovic111/horizon/issues/1434)
+- **Animated textures on the GPU** (v0.2.5): Water, lava and other animated blocks are now animated by the graphics card: 1.7 to 2.4 times better 1% lows on Intel graphics. [#1239](https://github.com/ludovic111/horizon/issues/1239)
+- **Far Detail for integrated graphics** (v0.2.5): An optional Reduced setting for far terrain, suggested on integrated graphics, that saves 2 to 4 ms of GPU time per frame. [#1199](https://github.com/ludovic111/horizon/issues/1199) · [#1029](https://github.com/ludovic111/horizon/issues/1029)
+- **The launcher's mod browser** (launcher@0.2.0): Search Modrinth for mods, modpacks and resource packs from the launcher; it says before installing what works in Horizon. [#1154](https://github.com/ludovic111/horizon/issues/1154) · [#1242](https://github.com/ludovic111/horizon/issues/1242) · [#1243](https://github.com/ludovic111/horizon/issues/1243) · [#1246](https://github.com/ludovic111/horizon/issues/1246) · [docs/mod-browser.md](docs/mod-browser.md)
+- **A blocky, Minecraft-like launcher** (launcher@0.2.0): The launcher got a new blocky look in Horizon's purple, in dark and light. [#1269](https://github.com/ludovic111/horizon/issues/1269) · [docs/design-system.md](docs/design-system.md)
+- **Dynamic lights** (v2026.10.22): An optional extra: torches you hold, drop or set on fire light up what is around them. [#1162](https://github.com/ludovic111/horizon/issues/1162)
+- **Host a server from the launcher** (launcher-v0.15.0): The launcher's Servers page creates, starts, backs up and updates a Horizon server with buttons, and invites friends. [#1026](https://github.com/ludovic111/horizon/issues/1026) · [docs/hosting.md](docs/hosting.md)
diff --git a/roadmap/README.md b/roadmap/README.md
new file mode 100644
index 000000000..df44575a5
--- /dev/null
+++ b/roadmap/README.md
@@ -0,0 +1,56 @@
+# The roadmap
+
+`roadmap.toml` is the one source of the roadmap. `tools/roadmap.py build` turns it into
+[ROADMAP.md](../ROADMAP.md); the website's hub (playhorizon.dev/hub) and Kira read the same items. The work
+board stays the task-level view (every issue and pull request); the roadmap is the overview, and each pull
+request carries the `roadmap:` label of the item it moves.
+
+## An item
+
+```toml
+[[item]]
+id = "server-dialogs" # lowercase words joined by dashes; never renamed (votes and links use it)
+title = "Server dialogs and login screens"
+status = "now" # now | next | later | help-wanted | shipped
+area = "servers" # one of the [[area]] ids, listed in the order of priority
+focus = true # optional: one of the 3 to 5 Now items in the overview
+ongoing = true # optional: a workstream that goes on after its pull requests merge
+plain = """Servers that show dialogs ... will work in Horizon.""" # players' words, at most 240 characters
+dev = """26.3's dialog packets and model (#1720), ...""" # crates, approach, what is left
+links = ["#1720", "#1734", "docs/hosting.md"] # #N, a repository path, or https://
+shipped_in = "v0.2.58" # shipped items only: a game tag, launcher@x.y.z, or "website"
+post = "..." # optional: the announcement when it ships, if `plain` doesn't read as one
+```
+
+- **No dates, ever**: Now, Next, Later. The check rejects month names, years, quarters and "next week".
+ "Coming soon" is the only phrase for something waiting on someone else (Microsoft sign-in, CurseForge).
+- **Only what is decided.** Ideas stay in issues and in the suggestion queue until they are.
+- **Only what is true in a release** for shipped items: a merged pull request isn't shipped until a release has it.
+- `plain` is for players: what they will be able to do, not how. `dev` is for contributors: the code, the
+ vanilla classes, the pull requests, what is left. Both stay public: no machines, accounts or private notes.
+- Help wanted items are good first contributions: a clear vanilla behaviour, an issue with steps, a place to
+ start in `dev`.
+
+## Keeping it current
+
+Whoever moves the work (the orchestrator on each heartbeat, or anyone in their pull request):
+
+1. `python3 tools/roadmap.py sync`: every item whose linked pull requests all went out in a release, whose
+ linked issues are all closed and that isn't `ongoing` becomes `shipped`, with that release in
+ `shipped_in`, on top of the shipped items. It rewrites `roadmap.toml` and ROADMAP.md; open a pull request
+ with the change (`skip-release`).
+2. `python3 tools/roadmap.py check`: the file's rules, then GitHub's state of every link. It fails when a
+ link is not an issue or pull request, when a Now item has no open pull request and none merged in the last
+ 14 days (link the new work, or move it to Next or Later), and when every link of a Help wanted item is
+ closed. It also says which items `sync` will ship once a release has them.
+3. When work starts, opens a pull request or is decided: add or move the item, add its links, then
+ `python3 tools/roadmap.py build`. Keep the overview's focus to the 3 to 5 biggest Now items.
+4. `python3 tools/roadmap.py labels` (after the change merges): creates a `roadmap:` label for each new
+ item, updates their colour (by status) and description, and adds the label to the open pull requests an item
+ links. Label a new pull request for an item by hand or by linking it and running `labels` again. Labels of
+ removed items are listed, never deleted.
+5. Suggestions from the website and Discord are read and triaged by the maintainers. A good one becomes an
+ item in a normal pull request; none is published automatically.
+
+CI runs `tests/test_roadmap.py` (in the Python tests), which fails when ROADMAP.md is not what `build` writes
+or when the file breaks a rule; `python3 tools/roadmap.py check --offline` runs the same rules without GitHub.
diff --git a/roadmap/roadmap.toml b/roadmap/roadmap.toml
new file mode 100644
index 000000000..bb664d3d5
--- /dev/null
+++ b/roadmap/roadmap.toml
@@ -0,0 +1,477 @@
+# Horizon's roadmap: the one source of truth for ROADMAP.md, playhorizon.dev/roadmap and Kira's answers.
+# Edit this file, then run `python3 tools/roadmap.py build`. How to keep it current: roadmap/README.md.
+#
+# No dates, ever: an item is Now, Next or Later. Each item says the same thing twice: `plain` for players
+# (one or two sentences, at most 240 characters, so it fits a post when it ships) and `dev` for contributors
+# (crates, approach, what is left). Links are "#123" (an issue or a pull request), a path in the repository,
+# or an https URL. Only what is decided goes here; ideas wait in GitHub issues and the suggestion queue.
+# `focus = true` puts a Now item in the overview (3 to 5 of them). `ongoing = true` marks a workstream that goes on
+# after its linked pull requests merge: `sync` never ships it, so link its new pull requests as they open.
+
+[overview]
+today_plain = """Horizon is Minecraft: Java Edition 26.3 rewritten from scratch in Rust, so it runs faster on the \
+same computer. Single player, LAN, servers, resource packs and Horizon's own mods work today, on your own copy of \
+the game."""
+today_dev = """A native Rust and wgpu reimplementation of Java 26.3: the same saves, rules and terrain, checked \
+against the real game by more than 300 differential harnesses (a Java oracle and a Rust probe on the same inputs). \
+Single player runs on its own server thread, like vanilla's integrated server."""
+help_plain = """Play it and tell us what differs from vanilla (Discord or GitHub), run the benchmark on your \
+computer, vote for what you want next, or pick one of the Help wanted items."""
+help_dev = """Read CONTRIBUTING.md, pick a Help wanted item or a To do card, check vanilla's code for the \
+behaviour, and paste the block `python3 tools/pr_ready.py` prints in your pull request."""
+
+# Areas, in the project's order of priority: performance first, then modpacks and servers.
+[[area]]
+id = "performance"
+name = "Performance"
+
+[[area]]
+id = "modpacks"
+name = "Modpacks"
+
+[[area]]
+id = "servers"
+name = "Servers and multiplayer"
+
+[[area]]
+id = "mods"
+name = "Mods and API"
+
+[[area]]
+id = "gameplay"
+name = "Gameplay parity"
+
+[[area]]
+id = "rendering"
+name = "Rendering"
+
+[[area]]
+id = "launcher"
+name = "Launcher"
+
+[[area]]
+id = "extras"
+name = "Horizon extras"
+
+[[area]]
+id = "project"
+name = "Code and tools"
+
+# ---------------------------------------------------------------------------------------------------- Now
+
+[[item]]
+id = "smooth-frames"
+title = "Steady frames at long render distances"
+status = "now"
+area = "performance"
+focus = true
+plain = """Making Horizon faster than vanilla on every computer, with smooth camera movement even at 32 chunks, \
+by spreading the work better over the processor's cores."""
+dev = """Frame pacing at render distance 32 (#678): long frames come from work competing with the render thread. \
+In review: world generation workers build free structure starts instead of queueing them (#1760), the worker pool \
+leaves one core as vanilla does (#1778), and the terrain vertex arena is read as storage where flat draws run \
+(#1742). Still open: far terrain at 48 to 64 chunks (#718) and CPU-bound fields of block entities (#717). Every \
+change shows before and after numbers from `tools/perf_bench.py` against vanilla 26.3 (docs/benchmark.md)."""
+links = ["#678", "#1760", "#1778", "#1742", "#718", "#717", "docs/benchmark.md"]
+
+[[item]]
+id = "block-storage"
+title = "Faster block lookups"
+status = "now"
+area = "performance"
+plain = """Speeding up the code that reads and writes the blocks of the world, which almost everything in the game \
+goes through: generation, lighting, meshing and ticking."""
+dev = """`PalettedContainer` and `PackedStorage` find an entry's word by multiply and shift instead of an integer \
+division (#1790, #1794); meshing looks up baked models by index, not by name (#1747). Each change keeps the paletted \
+storage harnesses identical and shows its microbenchmark (docs/performance/paletted-container-access-results.md)."""
+links = ["#1790", "#1794", "#1747", "docs/performance/paletted-container-access-results.md"]
+
+[[item]]
+id = "modpack-worldgen"
+title = "Modpacks' world generation, natively"
+status = "now"
+area = "modpacks"
+focus = true
+plain = """Making the world-generation mods of popular modpacks (new structures, YUNG's dungeons and mineshafts, \
+packs built on Lithostitched) generate their worlds in Horizon, natively and fast."""
+dev = """`horizon-port-pack` carries a pack's data-driven content over; structure mods that need code get a native \
+port: YUNG's worldgen as written (#1746), Lithostitched's limited and guaranteed elements with pool and processor \
+modifiers (#1777), its processors as the game's own types (#1765). Proved by the structure blocks and layout \
+harnesses (#1753, #1757). Mods whose Java code does more than world generation don't run (docs/modpacks.md)."""
+links = ["#1746", "#1777", "#1765", "#1753", "#1757", "docs/modpacks.md"]
+
+[[item]]
+id = "server-clients"
+title = "Playing on servers: everything shows as it should"
+status = "now"
+ongoing = true
+area = "servers"
+focus = true
+plain = """When you play on a server, other players, mobs, items and menus look and behave as in vanilla: skins, \
+poses, item names, inventories and server networks."""
+dev = """Client-of-a-server fixes in `game/remote*.rs` and `horizon-protocol`: mobs' aggressive and item-use flags \
+(#1802, #1798), ghost items after a remote menu (#1795), skins (#1652), cookies and transfer packets for proxy \
+networks (#1650), firework boosts (#1671), living-entity attributes and simulation distance (#1731), styled item \
+names (#1702), primed TNT between updates (#1710)."""
+links = ["#1802", "#1798", "#1795", "#1652", "#1650", "#1671", "#1731", "#1702", "#1710"]
+
+[[item]]
+id = "server-thread"
+title = "Single player as a server: the last differences"
+status = "now"
+ongoing = true
+area = "gameplay"
+focus = true
+plain = """Single player now runs a small server in the background, as vanilla does. We are fixing what still \
+behaves differently there; every fix also works for LAN and server players."""
+dev = """Since #1514 single player runs on the server thread (`game/integrated.rs`) and the window joins it as a \
+client; `--in-frame` keeps the old path. The open `[server-thread]` issues list the gaps. In review: a tool that \
+changes a block ends the click (#1797), potions keep their potion over the connection (#1796), mobs' aggression \
+and arm swings (#1802). docs/server-levels.md."""
+links = ["#1514", "#1797", "#1796", "#1802", "docs/server-levels.md"]
+
+[[item]]
+id = "mod-registry"
+title = "Horizon's mod registry"
+status = "now"
+area = "mods"
+focus = true
+plain = """One place for mods, modpacks and resource packs made for Horizon: browse them on the website and \
+install them from the launcher in one click."""
+dev = """Merged: the registry index (schema 1, `.hpack`, checks before install, #1634), `cargo horizon-mod check` \
+(#1642) and the submission service (`crates/horizon-mod-registry`, #1659). In review: the website's /mods (#1596) \
+and /mods/submit (#1635), and in the launcher the registry as a source (#1636), install, enable and takedowns \
+(#1637), the Mods page (#1638) and modpacks as their own profiles (#1640)."""
+links = ["#1634", "#1642", "#1659", "#1596", "#1635", "#1636", "#1637", "#1638", "#1640", "docs/mods.md"]
+
+[[item]]
+id = "server-dialogs"
+title = "Server dialogs and login screens"
+status = "now"
+area = "servers"
+plain = """Servers that show dialogs, such as the register and login screens of AuthMe, will work in Horizon."""
+dev = """26.3's dialog packets and model (#1720), the dialog screen with its buttons and actions (#1734), then text \
+and boolean inputs (#1735)."""
+links = ["#1720", "#1734", "#1735"]
+
+[[item]]
+id = "languages"
+title = "Play in your language"
+status = "now"
+area = "gameplay"
+plain = """Item names, container titles and server messages follow the language you pick, as in vanilla. Today \
+parts of the game stay in English."""
+dev = """Translatable components resolved through the selected language for items, containers and server text \
+(#1806), on top of the bundled languages the prepared resources carry (#1594). Left: the client's own screens \
+(#1672) and the main menu with zh_cn (#1774)."""
+links = ["#1806", "#1594", "#1672", "#1774"]
+
+[[item]]
+id = "shader-packs"
+title = "Shader packs, written again from scratch"
+status = "now"
+ongoing = true
+area = "rendering"
+plain = """Shader packs were removed and are being rebuilt from scratch. They come back, off by default, once the \
+best-known packs draw properly."""
+dev = """A clean-room rewrite in `horizon-shaderpack`, from the packs' public format documentation only: reading \
+packs, the preprocessor and `.properties` files are merged (#1584, #1585, #1586); translating programs to WGSL \
+through naga, buffers, uniforms and the terrain, entity, sky, weather and hand stages are in review (#1698 to \
+#1801)."""
+links = ["#1561", "#1584", "#1586", "#1698", "#1771", "#1786", "#1801"]
+
+[[item]]
+id = "discord-presence"
+title = "Discord Rich Presence"
+status = "now"
+area = "extras"
+plain = """Your Discord profile can show that you are playing Horizon, with a switch to turn it off."""
+dev = """A Discord IPC client on its own thread (#1787) and the presence with its setting (#1788). Merged: it ships \
+with the next release."""
+links = ["#1787", "#1788"]
+
+[[item]]
+id = "lean-code"
+title = "A leaner codebase that builds faster"
+status = "now"
+ongoing = true
+area = "project"
+plain = """Cleaning up Horizon's code: removing what nothing uses and making it quicker to build, so fixes and new \
+features land faster."""
+dev = """A review of the whole tree: dead code and stubs removed (#1432, #1658), one probe binary per crate (#1453, \
+#1454), shared harness helpers (#1448), clippy clean on the whole tree (#1707). docs/architecture.md maps each \
+feature to its files and harnesses."""
+links = ["#1432", "#1658", "#1453", "#1454", "#1448", "#1707", "docs/architecture.md"]
+
+# ---------------------------------------------------------------------------------------------------- Next
+
+[[item]]
+id = "microsoft-sign-in"
+title = "Microsoft sign-in (coming soon)"
+status = "next"
+area = "launcher"
+plain = """Coming soon: sign in with your Microsoft account to play on online-mode servers. The code is ready; it \
+waits for Microsoft's approval."""
+dev = """Device-code sign-in in the launcher and online-mode login in the client (docs/microsoft-account.md). It is \
+turned on by setting the app's client id once Minecraft API access is approved; until then the launcher shows \
+"Coming soon"."""
+links = ["docs/microsoft-account.md", "#1270"]
+
+[[item]]
+id = "curseforge"
+title = "CurseForge in the mod browser (coming soon)"
+status = "next"
+area = "modpacks"
+plain = """Coming soon: search and download CurseForge mods and modpacks from the launcher, as you can with \
+Modrinth today."""
+dev = """The mod browser lists CurseForge as coming soon (docs/mod-browser.md): it needs CurseForge API access. \
+Meanwhile packs import from a CurseForge zip or instance folder, and jars only CurseForge hosts come from the \
+player's own instance (docs/modpacks.md)."""
+links = ["docs/mod-browser.md", "docs/modpacks.md"]
+
+[[item]]
+id = "benchmarks"
+title = "Fresh benchmarks against vanilla"
+status = "next"
+area = "performance"
+plain = """New public numbers comparing Horizon with vanilla on many kinds of computers, measured the same way \
+every time, on the website's Benchmarks page."""
+dev = """Redo the comparison after the current performance work (#1073); reliability, coverage and presentation \
+(#1346); a scene must count as loaded only once its first chunk arrives (#1749). Players' reports come in through \
+`--benchmark` and `horizon-launcher data benchmark` (docs/benchmark.md)."""
+links = ["#1073", "#1346", "#1749", "docs/benchmark.md"]
+
+[[item]]
+id = "pistons-push"
+title = "Pistons push players and mobs"
+status = "next"
+area = "gameplay"
+plain = """Pistons and slime blocks will push players, mobs and items as in vanilla. Today moving blocks pass \
+through them."""
+dev = """Port `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` (honey), the slime bounce and \
+`Entity.limitPistonMovement` for `MoverType.PISTON`, in single player and for a server's players. Issues #1496, \
+#1609, #1608, #1704, #1758."""
+links = ["#1496", "#1609", "#1608", "#1704", "#1758"]
+
+[[item]]
+id = "intel-mac"
+title = "Horizon on Intel Macs"
+status = "next"
+area = "launcher"
+plain = """Builds of the game and the launcher for Macs with an Intel processor."""
+dev = """x86_64 game and launcher builds, picked per processor (#1171). Before it ships it needs a run on a real \
+Intel Mac: Rosetta on Apple Silicon only proves the CPU code. Requests: #1161, #1792."""
+links = ["#1171", "#1161", "#1792"]
+
+# ---------------------------------------------------------------------------------------------------- Later
+
+[[item]]
+id = "ai-companion"
+title = "An optional AI teammate"
+status = "later"
+area = "extras"
+plain = """An AI teammate that plays beside you and that you can talk to. It is off unless you turn it on, and the \
+No AI switch hides it completely."""
+dev = """Draft pull requests: the companion (#1068), its safety modes and their evaluation (#1069), and a route \
+that finishes the game (#1070). Local models first; it ships only once the safety evaluation passes."""
+links = ["#1068", "#1069", "#1070"]
+
+[[item]]
+id = "new-versions"
+title = "Following new Minecraft versions"
+status = "later"
+area = "gameplay"
+plain = """When Mojang releases a new version of the game, Horizon follows it, and every system is checked against \
+the new version again."""
+dev = """The port pipeline detects a release, diffs its classes against 26.3 and writes a port report \
+(docs/version-ports.md); the harnesses then run against the new version."""
+links = ["docs/version-ports.md"]
+
+# ---------------------------------------------------------------------------------------------------- Help wanted
+
+[[item]]
+id = "benchmark-your-pc"
+title = "Benchmark your computer"
+status = "help-wanted"
+area = "performance"
+plain = """Run Horizon's built-in benchmark and share the report: every new computer makes the performance work \
+more accurate. No coding needed."""
+dev = """`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data \
+benchmark ` shows what would be sent and uploads it (website/docs/performance.md). Results from three \
+installs with the same hardware appear on the Benchmarks page. Example: #1711."""
+links = ["website/docs/performance.md", "#1711"]
+
+[[item]]
+id = "end-city-banners"
+title = "End city banners keep their pattern"
+status = "help-wanted"
+area = "gameplay"
+plain = """Banners in End cities show as plain magenta instead of with their pattern."""
+dev = """Compare the banner block entities the End city templates place with vanilla's (`EndCityPieces`, the \
+templates' block entity NBT, `BannerBlockEntity`'s patterns), in `crates/horizon-world/src/worldgen/structure/`. \
+Issue #1438; possibly related: #526."""
+links = ["#1438", "#526"]
+
+[[item]]
+id = "end-city-loot"
+title = "Enchanted loot in End cities"
+status = "help-wanted"
+area = "gameplay"
+plain = """Armour and tools in End city chests should come enchanted, as in vanilla."""
+dev = """`loot.rs` implements `enchant_with_levels`: find why the End city chest table's rolls come out bare, and \
+compare them with vanilla's for a few seeds. Issues #1437, #1660."""
+links = ["#1437", "#1660"]
+
+[[item]]
+id = "item-cooldowns"
+title = "Cooldowns drawn on items"
+status = "help-wanted"
+area = "gameplay"
+plain = """After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla."""
+dev = """Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot \
+(`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue #1763."""
+links = ["#1763"]
+
+[[item]]
+id = "chat-settings"
+title = "Chat settings and team prefixes"
+status = "help-wanted"
+area = "gameplay"
+plain = """The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before \
+names in chat."""
+dev = """Vanilla checks `ChatVisiblity` before it delivers chat and system messages (#1376), and chat uses the \
+team-formatted display name (#1378). Both issues have exact steps to reproduce."""
+links = ["#1376", "#1378"]
+
+[[item]]
+id = "pointer-hand"
+title = "A pointing hand over buttons"
+status = "help-wanted"
+area = "gameplay"
+plain = """The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3."""
+dev = """26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's \
+`CursorIcon::Pointer` gives the same shape. Issue #1347."""
+links = ["#1347"]
+
+[[item]]
+id = "text-field-keys"
+title = "Ctrl+Backspace and scroll bars in menus"
+status = "help-wanted"
+area = "gameplay"
+plain = """Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be \
+draggable."""
+dev = """`EditBox` deletes by word with Ctrl (#1764); the Game Rules and Statistics lists' scroll bars can't be \
+dragged (#1782, after #978)."""
+links = ["#1764", "#1782"]
+
+[[item]]
+id = "chicken-flap"
+title = "Chickens flap while they fall"
+status = "help-wanted"
+area = "gameplay"
+plain = """Chickens should flap their wings while they fall, not stand still in the air."""
+dev = """Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the \
+model's wings follow them. Issue #1706."""
+links = ["#1706"]
+
+# ---------------------------------------------------------------------------------------------------- Shipped
+# Newest first: `tools/roadmap.py sync` adds each newly shipped item on top.
+
+[[item]]
+id = "server-resource-packs"
+title = "Server resource packs"
+status = "shipped"
+shipped_in = "v0.2.48"
+area = "servers"
+plain = """Servers can send you their resource pack: Horizon asks, downloads it and applies it, like vanilla."""
+dev = """The dedicated server offers server.properties' pack (#1562); the client's pack manager, downloads, prompt \
+and Server Resource Packs setting (#1569, #1570)."""
+links = ["#1562", "#1569", "#1570"]
+
+[[item]]
+id = "server-thread-default"
+title = "Single player on its own server thread"
+status = "shipped"
+shipped_in = "v0.2.39"
+area = "gameplay"
+plain = """Single player runs on a server thread, as vanilla does, so the world keeps ticking smoothly while the \
+window draws."""
+dev = """`game/integrated.rs` runs a second `Game` with one level per dimension; the window joins it through \
+memory like a LAN guest (#1514)."""
+links = ["#1514", "docs/server-levels.md"]
+
+[[item]]
+id = "metal-occlusion"
+title = "GPU occlusion culling on Macs"
+status = "shipped"
+shipped_in = "v0.2.17"
+area = "performance"
+plain = """On Macs the GPU now skips terrain hidden behind hills and caves: 8 to 48% more frames per second at 32 \
+chunks on an M4 Pro."""
+dev = """GPU occlusion culling on Metal (#1434)."""
+links = ["#1434"]
+
+[[item]]
+id = "gpu-animated-textures"
+title = "Animated textures on the GPU"
+status = "shipped"
+shipped_in = "v0.2.5"
+area = "performance"
+plain = """Water, lava and other animated blocks are now animated by the graphics card: 1.7 to 2.4 times better 1% \
+lows on Intel graphics."""
+dev = """Frames uploaded once, no per-tick CPU blend or copy (#1239)."""
+links = ["#1239"]
+
+[[item]]
+id = "far-detail"
+title = "Far Detail for integrated graphics"
+status = "shipped"
+shipped_in = "v0.2.5"
+area = "performance"
+plain = """An optional Reduced setting for far terrain, suggested on integrated graphics, that saves 2 to 4 ms of GPU \
+time per frame."""
+dev = """Opt-in reduced far terrain (#1199), on far-terrain chunk summaries built on the workers (#1029)."""
+links = ["#1199", "#1029"]
+
+[[item]]
+id = "mod-browser"
+title = "The launcher's mod browser"
+status = "shipped"
+shipped_in = "launcher@0.2.0"
+area = "modpacks"
+plain = """Search Modrinth for mods, modpacks and resource packs from the launcher; it says before installing what \
+works in Horizon."""
+dev = """The Mods page (#1154), Java mods checked before install (#1242), project pages, filters and galleries \
+(#1243), modpacks ported in the same step (#1246). docs/mod-browser.md."""
+links = ["#1154", "#1242", "#1243", "#1246", "docs/mod-browser.md"]
+
+[[item]]
+id = "launcher-look"
+title = "A blocky, Minecraft-like launcher"
+status = "shipped"
+shipped_in = "launcher@0.2.0"
+area = "launcher"
+plain = """The launcher got a new blocky look in Horizon's purple, in dark and light."""
+dev = """The Blocks look (#1269), from `horizon-theme` (docs/design-system.md)."""
+links = ["#1269", "docs/design-system.md"]
+
+[[item]]
+id = "dynamic-lights"
+title = "Dynamic lights"
+status = "shipped"
+shipped_in = "v2026.10.22"
+area = "extras"
+plain = """An optional extra: torches you hold, drop or set on fire light up what is around them."""
+dev = """Held, dropped and burning light sources (#1162), in Horizon Extras, off by default."""
+links = ["#1162"]
+
+[[item]]
+id = "servers-page"
+title = "Host a server from the launcher"
+status = "shipped"
+shipped_in = "launcher-v0.15.0"
+area = "servers"
+plain = """The launcher's Servers page creates, starts, backs up and updates a Horizon server with buttons, and \
+invites friends."""
+dev = """The launcher's Servers page (#1026) over `horizon-server` (docs/hosting.md)."""
+links = ["#1026", "docs/hosting.md"]
diff --git a/tests/test_roadmap.py b/tests/test_roadmap.py
new file mode 100644
index 000000000..fb4f4e419
--- /dev/null
+++ b/tests/test_roadmap.py
@@ -0,0 +1,207 @@
+import copy
+import datetime
+import tomllib
+import unittest
+from unittest import mock
+
+from tools import roadmap
+
+SAMPLE = '''[overview]
+today_plain = "a"
+today_dev = "b"
+help_plain = "c"
+help_dev = "d"
+
+[[area]]
+id = "performance"
+name = "Performance"
+
+# ---- Now
+
+[[item]]
+id = "fast"
+title = "Fast"
+status = "now"
+area = "performance"
+focus = true
+plain = "Faster."
+dev = """Multiply, \\
+not divide (#10)."""
+links = ["#10"]
+
+[[item]]
+id = "faster"
+title = "Faster"
+status = "now"
+area = "performance"
+focus = true
+plain = "Even faster."
+dev = "More (#11)."
+links = ["#11", "#12"]
+
+[[item]]
+id = "fastest"
+title = "Fastest"
+status = "now"
+area = "performance"
+focus = true
+ongoing = true
+plain = "The fastest."
+dev = "Most (#13)."
+links = ["#13"]
+
+# ---- Shipped
+
+[[item]]
+id = "old"
+title = "Old"
+status = "shipped"
+shipped_in = "v0.2.1"
+area = "performance"
+plain = "Done."
+dev = "Done (#1)."
+links = ["#1"]
+'''
+
+
+def pull(state, merged_at=None, paths=("crates/horizon-client/src/game.rs",)):
+ return {"kind": "PullRequest", "state": state, "merged_at": merged_at, "merge_commit": "abc" if merged_at else None,
+ "paths": list(paths)}
+
+
+def issue(state):
+ return {"kind": "Issue", "state": state, "merged_at": None, "merge_commit": None, "paths": []}
+
+
+class RepositoryRoadmap(unittest.TestCase):
+ def test_the_roadmap_keeps_its_rules(self):
+ self.assertEqual(roadmap.validate(roadmap.load()), [])
+
+ def test_roadmap_md_is_generated_from_the_toml(self):
+ self.assertEqual(roadmap.OUTPUT.read_text(), roadmap.render(roadmap.load()),
+ "ROADMAP.md is out of date: run `python3 tools/roadmap.py build`")
+
+
+class Rules(unittest.TestCase):
+ def setUp(self):
+ self.data = tomllib.loads(SAMPLE)
+
+ def problems(self, **changes):
+ data = copy.deepcopy(self.data)
+ data["item"][0].update(changes)
+ return roadmap.validate(data)
+
+ def test_the_sample_is_valid(self):
+ self.assertEqual(roadmap.validate(self.data), [])
+
+ def test_unknown_status_area_and_key(self):
+ self.assertTrue(any("status" in p for p in self.problems(status="soon")))
+ self.assertTrue(any("area" in p for p in self.problems(area="nowhere")))
+ self.assertTrue(any("unknown key" in p for p in self.problems(eta="soon")))
+
+ def test_plain_fits_a_post(self):
+ self.assertTrue(any("at most 240" in p for p in self.problems(plain="x" * 241)))
+ self.assertTrue(any("post" in p for p in self.problems(post="x" * 241)))
+
+ def test_shipped_needs_its_release(self):
+ self.assertTrue(any("shipped_in" in p for p in self.problems(status="shipped", focus=False)))
+ self.assertTrue(any("only shipped" in p for p in self.problems(shipped_in="v0.2.3")))
+ self.assertTrue(any("not a release" in p for p in self.problems(status="shipped", focus=False,
+ shipped_in="soon")))
+
+ def test_links_are_issues_urls_or_repository_paths(self):
+ self.assertEqual(self.problems(links=["#4", "https://playhorizon.dev", "docs/benchmark.md"]), [])
+ self.assertTrue(any("link" in p for p in self.problems(links=["docs/nothing-here.md"])))
+ self.assertTrue(any("link" in p for p in self.problems(links=["http://example.com"])))
+
+ def test_three_to_five_items_in_focus(self):
+ self.assertTrue(any("focus" in p for p in self.problems(focus=False)))
+
+ def test_no_dates(self):
+ for text in ("Ready in March.", "Before 2027.", "In Q3.", "Next week.", "In 3 weeks.", "By the end of it."):
+ self.assertTrue(roadmap.dated(text), text)
+ for text in ("Coming soon.", "Pull request #2026.", "Java 26.3.", "Mobs march on.", "It may land."):
+ self.assertIsNone(roadmap.dated(text), text)
+ self.assertTrue(any("date" in p for p in self.problems(plain="Done in October.")))
+
+
+class Render(unittest.TestCase):
+ def test_sections_links_and_the_overview(self):
+ text = roadmap.render(tomllib.loads(SAMPLE))
+ self.assertIn("## Now", text)
+ self.assertIn("## Recently shipped", text)
+ self.assertNotIn("## Later", text)
+ self.assertIn("- **Fast**: Faster.", text)
+ self.assertIn("Multiply, not divide ([#10](https://github.com/ludovic111/horizon/issues/10)).", text)
+ # A link the technical text already gives isn't repeated; the others are listed after it.
+ self.assertIn("More: [#12](https://github.com/ludovic111/horizon/issues/12)", text)
+ self.assertIn("- **Old** (v0.2.1): Done.", text)
+
+
+class GitHubState(unittest.TestCase):
+ now = datetime.datetime(2030, 1, 20, tzinfo=datetime.timezone.utc)
+
+ def test_a_now_item_without_live_pull_requests_is_stale(self):
+ data = tomllib.loads(SAMPLE)
+ states = {1: pull("MERGED", "2029-12-01T00:00:00Z"), 10: pull("OPEN"),
+ 11: pull("MERGED", "2029-11-01T00:00:00Z"), 12: issue("OPEN"),
+ 13: pull("MERGED", "2030-01-19T00:00:00Z")}
+ problems, notes = roadmap.online_problems(data, states, self.now)
+ self.assertEqual(len(problems), 1)
+ self.assertIn("faster: stale", problems[0])
+ self.assertTrue(any("fastest: ongoing" in note for note in notes))
+
+ def test_missing_numbers_are_reported(self):
+ problems, _ = roadmap.online_problems(tomllib.loads(SAMPLE), {}, self.now)
+ self.assertTrue(any("#10 is neither" in p for p in problems))
+
+
+class Labels(unittest.TestCase):
+ def test_creates_updates_and_adds_labels(self):
+ data = tomllib.loads(SAMPLE)
+ existing = {"roadmap:fast": {"color": "5B3FD6", "description": "Roadmap, now: Fast"},
+ "roadmap:faster": {"color": "000000", "description": "old"},
+ "roadmap:gone": {"color": "000000", "description": ""}}
+ states = {10: dict(pull("OPEN"), labels=["roadmap:fast"]), 11: dict(pull("OPEN"), labels=[]),
+ 13: dict(pull("MERGED", "2030-01-01T00:00:00Z"), labels=[])}
+ changes, stale = roadmap.label_changes(data, existing, states)
+ self.assertEqual([(action, target) for action, target, _ in changes],
+ [("update", "roadmap:faster"), ("add", 11), ("create", "roadmap:fastest"),
+ ("create", "roadmap:old")])
+ self.assertEqual(changes[0][2]["color"], "5b3fd6")
+ self.assertEqual(stale, ["roadmap:gone"])
+
+
+class Sync(unittest.TestCase):
+ def test_family_of_a_change(self):
+ self.assertEqual(roadmap.family(["launcher/src/main.rs"]), "launcher")
+ self.assertEqual(roadmap.family(["website/src/main.js"]), "website")
+ self.assertEqual(roadmap.family(["launcher/src/main.rs", "crates/x/src/lib.rs"]), "game")
+
+ def test_merged_and_released_items_move_to_the_top_of_shipped(self):
+ data = tomllib.loads(SAMPLE)
+ states = {10: pull("MERGED", "2030-01-02T00:00:00Z"), 11: pull("MERGED", "2030-01-03T00:00:00Z"),
+ 12: issue("OPEN"), 13: pull("MERGED", "2030-01-03T00:00:00Z")}
+ with mock.patch.object(roadmap, "first_release", return_value="v0.2.9") as release:
+ text, log = roadmap.sync(data, SAMPLE, states)
+ release.assert_called_once_with("abc", "game")
+ # "faster" keeps an open issue and "fastest" is ongoing: only "fast" ships.
+ self.assertEqual(log, ["fast: shipped in v0.2.9"])
+ new = tomllib.loads(text)
+ self.assertEqual([item["id"] for item in new["item"]], ["faster", "fastest", "fast", "old"])
+ fast = new["item"][2]
+ self.assertEqual((fast["status"], fast["shipped_in"]), ("shipped", "v0.2.9"))
+ self.assertNotIn("focus", fast)
+ self.assertEqual(fast["dev"], "Multiply, not divide (#10).")
+ self.assertIn("# ---- Shipped\n\n[[item]]\nid = \"fast\"", text)
+
+ def test_merged_but_unreleased_items_wait(self):
+ states = {10: pull("MERGED", "2030-01-02T00:00:00Z")}
+ with mock.patch.object(roadmap, "first_release", return_value=None):
+ text, log = roadmap.sync(tomllib.loads(SAMPLE), SAMPLE, states)
+ self.assertEqual(text, SAMPLE)
+ self.assertEqual(log, ["fast: merged, waiting for a release"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/pr_ready.py b/tools/pr_ready.py
index a944e2116..505de28c1 100755
--- a/tools/pr_ready.py
+++ b/tools/pr_ready.py
@@ -108,7 +108,7 @@ def touched_crates(paths, packages):
def area(path):
"""The part of the project a path belongs to; None for what goes with any change (docs, tests, harnesses)."""
- if is_doc(path) or path.startswith(("tests/", "mods/", "docs/")) or path == "research-lock.json" or \
+ if is_doc(path) or path.startswith(("tests/", "mods/", "docs/", "roadmap/")) or path == "research-lock.json" or \
(path.startswith("tools/") and not path.startswith("tools/ci/")):
return None
if path.startswith(("launcher/", "crates/horizon-prepare/")):
@@ -288,7 +288,9 @@ def plan(args, base, changed, crates_of, libraries, dependencies):
"""The checks for these changed files, in the order they run."""
rust = any(workspace_rust(path) for path in changed)
launcher = any(launcher_rust(path) for path in changed)
- python = any(path.endswith(".py") or path.startswith(("tests/", "tools/")) for path in changed)
+ # The Python tests also hold ROADMAP.md to roadmap/roadmap.toml (tests/test_roadmap.py).
+ python = any(path.endswith(".py") or path.startswith(("tests/", "tools/", "roadmap/")) or path == "ROADMAP.md"
+ for path in changed)
crates = touched_crates(changed, crates_of) if rust or TOKENS in changed else []
# An unrecognised Rust path must not silently skip validation.
if rust and crates == []:
diff --git a/tools/roadmap.py b/tools/roadmap.py
new file mode 100644
index 000000000..b1bb13c6d
--- /dev/null
+++ b/tools/roadmap.py
@@ -0,0 +1,551 @@
+#!/usr/bin/env python3
+"""Horizon's roadmap: roadmap/roadmap.toml is the source, ROADMAP.md is generated from it.
+
+ python3 tools/roadmap.py build write ROADMAP.md
+ python3 tools/roadmap.py build --check fail when ROADMAP.md is out of date (CI)
+ python3 tools/roadmap.py check --offline the file's own rules (CI)
+ python3 tools/roadmap.py check the same, then GitHub: links resolve, no stale Now item
+ python3 tools/roadmap.py sync [--dry-run] items whose pull requests all merged become shipped,
+ with the release they went out in
+ python3 tools/roadmap.py labels [--dry-run] a `roadmap:` label per item on GitHub, and on the open
+ pull requests the item links
+
+The online commands read GitHub with GITHUB_TOKEN, GH_TOKEN or `gh auth token`. Maintenance: roadmap/README.md.
+"""
+
+import argparse
+import datetime
+import json
+import os
+import re
+import subprocess
+import sys
+import tomllib
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+SOURCE = ROOT / "roadmap" / "roadmap.toml"
+OUTPUT = ROOT / "ROADMAP.md"
+REPO = "ludovic111/horizon"
+SITE = "https://playhorizon.dev/hub"
+
+STATUSES = {
+ "now": "Now",
+ "next": "Next",
+ "later": "Later",
+ "help-wanted": "Help wanted",
+ "shipped": "Recently shipped",
+}
+PLAIN_MAX = 240 # one post's worth, so a shipped item can be announced as written
+TITLE_MAX = 70
+FOCUS_RANGE = (3, 5)
+STALE_DAYS = 14 # a Now item needs an open pull request, or one merged this recently
+LABEL_PREFIX = "roadmap:"
+# GitHub label colours by status, from the design system's palette.
+LABEL_COLOURS = {"now": "5b3fd6", "next": "9a86ff", "later": "c5c7d1", "help-wanted": "1d7a48", "shipped": "646875"}
+ITEM_KEYS = {"id", "title", "status", "area", "plain", "dev", "links", "focus", "ongoing", "shipped_in", "post"}
+
+ISSUE = re.compile(r"#(\d+)$")
+ID = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*$")
+RELEASE = re.compile(r"(v\d[\w.]*|launcher@\d[\w.]*|launcher-v\d[\w.]*|website)$")
+MONTHS = ("January|February|March|April|June|July|August|September|October|November|December")
+# Kira's rule: no dates and no promises of when. "Coming soon" is the one allowed phrase.
+DATE = re.compile(
+ rf"\b(?:{MONTHS})\b|\bMay \d|(? TITLE_MAX:
+ problems.append(f"{where}: the title is longer than {TITLE_MAX} characters")
+ for key in ("plain", "post"):
+ if len(item.get(key, "")) > PLAIN_MAX:
+ problems.append(f"{where}: {key} is {len(item[key])} characters, at most {PLAIN_MAX}")
+ for key in ("title", "plain", "dev", "post"):
+ found = dated(item.get(key, ""))
+ if found:
+ problems.append(f"{where}: {key} names a date or a deadline ({found!r}); the roadmap has none")
+ shipped_in = item.get("shipped_in")
+ if status == "shipped":
+ if not shipped_in:
+ problems.append(f"{where}: a shipped item needs shipped_in (a release tag, or \"website\")")
+ elif not RELEASE.match(shipped_in):
+ problems.append(f"{where}: shipped_in {shipped_in!r} is not a release tag or \"website\"")
+ elif shipped_in:
+ problems.append(f"{where}: only shipped items have shipped_in")
+ if item.get("ongoing") and status not in ("now", "next", "later"):
+ problems.append(f"{where}: only Now, Next and Later items are ongoing")
+ if item.get("focus") and status != "now":
+ problems.append(f"{where}: only Now items can be in focus")
+ links = item.get("links", [])
+ if not isinstance(links, list):
+ problems.append(f"{where}: links is a list")
+ links = []
+ if not links and status != "later":
+ problems.append(f"{where}: needs at least one link (an issue, a pull request or a doc)")
+ for link in links:
+ if ISSUE.match(link) or link.startswith("https://"):
+ continue
+ if link.startswith(("/", "http:")) or ".." in link or not (root / link).exists():
+ problems.append(f"{where}: link {link!r} is neither #N, https:// nor a path in the repository")
+ focus = sum(1 for item in items if item.get("focus"))
+ low, high = FOCUS_RANGE
+ if not low <= focus <= high:
+ problems.append(f"focus: {focus} items are in focus, the overview wants {low} to {high}")
+ return problems
+
+
+def areas_in_order(data):
+ return [(area["id"], area["name"]) for area in data.get("area", [])]
+
+
+def by_area(data, status):
+ """The items of a status, grouped by area in the areas' order, each group in the file's order."""
+ items = [item for item in data.get("item", []) if item.get("status") == status]
+ return [(name, [item for item in items if item["area"] == key])
+ for key, name in areas_in_order(data) if any(item["area"] == key for item in items)]
+
+
+def linkify(text, links=()):
+ """Markdown links for the text's #N, and for the item's own paths and URLs where the text names them."""
+ text = re.sub(r"(?",
+ "",
+ "What is being done on Horizon, what comes next and where you can help. There are no dates: things are"
+ " Now, Next or Later. Each item is said in plain words, with the technical picture folded under it."
+ f" The same roadmap, with a Simple / Technical switch, the board, the journal and how to help, is on"
+ f" [playhorizon.dev/hub]({SITE}). Pull requests carry the `roadmap:` label of their item.",
+ "",
+ "## At a glance",
+ "",
+ overview["today_plain"].strip(),
+ "",
+ "**Being done now**",
+ "",
+ ]
+ out += [f"- **{item['title']}**: {item['plain'].strip()}" for item in items if item.get("focus")]
+ nexts = [item["title"] for item in items if item.get("status") == "next"]
+ if nexts:
+ out += ["", "**Next**: " + "; ".join(nexts) + "."]
+ out += ["", f"**How to help**: {overview['help_plain'].strip()}", "",
+ f"**Developers**: {overview['help_dev'].strip()}"]
+ for status, heading in STATUSES.items():
+ groups = by_area(data, status)
+ if not groups:
+ continue
+ out += ["", f"## {heading}"]
+ if status == "shipped":
+ # Newest first: the file's order, where `sync` puts each newly shipped item on top.
+ out += [""] + [f"- **{item['title']}** ({item['shipped_in']}): {item['plain'].strip()} "
+ f"{link_list(item['links'])}" for item in items if item.get("status") == status]
+ continue
+ for area, group in groups:
+ out += ["", f"### {area}"]
+ for item in group:
+ out += ["", f"#### {item['title']}", "", item["plain"].strip(), "",
+ "Technical ", "", linkify(item["dev"].strip(), item.get("links", []))]
+ more = [link for link in item.get("links", []) if not re.search(rf"{re.escape(link)}\b", item["dev"])]
+ if more:
+ out += ["", "More: " + link_list(more)]
+ out += ["", " "]
+ return "\n".join(out) + "\n"
+
+
+# --- GitHub ---------------------------------------------------------------------------------------------------
+
+def token():
+ for name in ("GITHUB_TOKEN", "GH_TOKEN"):
+ if os.environ.get(name):
+ return os.environ[name]
+ try:
+ return subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, check=True).stdout.strip()
+ except (OSError, subprocess.CalledProcessError):
+ sys.exit("roadmap: reading GitHub needs GITHUB_TOKEN, GH_TOKEN or `gh auth login` (or use --offline)")
+
+
+def numbers_in(data):
+ return sorted({int(ISSUE.match(link)[1]) for item in data.get("item", [])
+ for link in item.get("links", []) if ISSUE.match(link)})
+
+
+def github_states(numbers, auth):
+ """{number: {"kind": "Issue" | "PullRequest", "state", "merged_at", "merge_commit", "paths"}} for those
+ that exist, in one GraphQL request per hundred numbers."""
+ owner, name = REPO.split("/")
+ states = {}
+ for start in range(0, len(numbers), 100):
+ fields = "\n".join(
+ f"n{n}: issueOrPullRequest(number: {n}) {{ __typename "
+ "... on Issue { state } "
+ "... on PullRequest { state mergedAt mergeCommit { oid } files(first: 100) { nodes { path } } "
+ "labels(first: 50) { nodes { name } } } }"
+ for n in numbers[start:start + 100])
+ query = f'query {{ repository(owner: "{owner}", name: "{name}") {{ {fields} }} }}'
+ request = urllib.request.Request(
+ "https://api.github.com/graphql", data=json.dumps({"query": query}).encode(),
+ headers={"Authorization": f"bearer {auth}", "User-Agent": "horizon-roadmap"})
+ with urllib.request.urlopen(request, timeout=30) as response:
+ answer = json.load(response)
+ for key, node in (answer.get("data", {}).get("repository") or {}).items():
+ if node:
+ states[int(key[1:])] = {
+ "kind": node["__typename"],
+ "state": node["state"],
+ "merged_at": node.get("mergedAt"),
+ "merge_commit": (node.get("mergeCommit") or {}).get("oid"),
+ "paths": [file["path"] for file in ((node.get("files") or {}).get("nodes") or [])],
+ "labels": [label["name"] for label in ((node.get("labels") or {}).get("nodes") or [])],
+ }
+ return states
+
+
+def pull_requests(item, states):
+ return [states[n] for n in (int(ISSUE.match(link)[1]) for link in item.get("links", []) if ISSUE.match(link))
+ if n in states and states[n]["kind"] == "PullRequest"]
+
+
+def open_issues(item, states):
+ return [n for n in (int(ISSUE.match(link)[1]) for link in item.get("links", []) if ISSUE.match(link))
+ if n in states and states[n]["kind"] == "Issue" and states[n]["state"] == "OPEN"]
+
+
+def online_problems(data, states, now):
+ """What only GitHub can tell: links that don't exist, Now items nobody works on, Help wanted items already
+ done, items `sync` would ship."""
+ problems, notes = [], []
+ recent = now - datetime.timedelta(days=STALE_DAYS)
+ for item in data.get("item", []):
+ where = f"item {item['id']}"
+ for link in item.get("links", []):
+ match = ISSUE.match(link)
+ if match and int(match[1]) not in states:
+ problems.append(f"{where}: {link} is neither an issue nor a pull request of {REPO}")
+ pulls = pull_requests(item, states)
+ status = item.get("status")
+ if status == "now":
+ alive = [p for p in pulls if p["state"] == "OPEN" or
+ (p["merged_at"] and datetime.datetime.fromisoformat(p["merged_at"]) >= recent)]
+ if not alive:
+ problems.append(f"{where}: stale: Now, but no open pull request and none merged in the last "
+ f"{STALE_DAYS} days (link the work, or move it to Next or Later)")
+ if status == "help-wanted":
+ issues = [states[int(ISSUE.match(link)[1])] for link in item.get("links", [])
+ if ISSUE.match(link) and int(ISSUE.match(link)[1]) in states]
+ if issues and all(i["state"] != "OPEN" for i in issues):
+ problems.append(f"{where}: every linked issue and pull request is closed: ship or drop it")
+ if status != "shipped" and pulls and all(p["state"] == "MERGED" for p in pulls):
+ if item.get("ongoing"):
+ notes.append(f"{where}: ongoing, and all its pull requests merged: link the new ones")
+ elif not open_issues(item, states):
+ notes.append(f"{where}: all its pull requests merged: `python3 tools/roadmap.py sync` ships it "
+ "once a release has them")
+ return problems, notes
+
+
+# --- sync -----------------------------------------------------------------------------------------------------
+
+def family(paths):
+ """Which releases carry a change: the launcher's, the website (deployed from main) or the game's."""
+ if paths and all(path.startswith("launcher/") for path in paths):
+ return "launcher"
+ if paths and all(path.startswith("website/") for path in paths):
+ return "website"
+ return "game"
+
+
+def first_release(commit, kind):
+ """The oldest release tag of this kind that contains the commit, or None while none does."""
+ if kind == "website":
+ return "website"
+ tags = subprocess.run(["git", "tag", "--contains", commit, "--sort=creatordate"], cwd=ROOT,
+ capture_output=True, text=True).stdout.split()
+ wanted = (lambda tag: tag.startswith(("launcher@", "launcher-v"))) if kind == "launcher" else \
+ (lambda tag: re.match(r"v\d", tag))
+ return next((tag for tag in tags if wanted(tag)), None)
+
+
+def release_of(pulls):
+ """The release that shipped the last of these merged pull requests, or None."""
+ kinds = {family(p["paths"]) for p in pulls}
+ kind = "game" if "game" in kinds or len(kinds) > 1 else kinds.pop()
+ latest = max(pulls, key=lambda p: p["merged_at"])
+ return first_release(latest["merge_commit"], kind) if latest["merge_commit"] else None
+
+
+def item_span(lines, ident):
+ """[start, end) of the item's lines: its [[item]] header to its last key, without the comments that follow."""
+ starts = [i for i, line in enumerate(lines) if line.strip() == "[[item]]"]
+ for position, start in enumerate(starts):
+ end = starts[position + 1] if position + 1 < len(starts) else len(lines)
+ if not any(re.match(rf'id\s*=\s*"{re.escape(ident)}"\s*$', line) for line in lines[start:end]):
+ continue
+ while end > start and (not lines[end - 1].strip() or re.match(r"#(\s|-|$)", lines[end - 1])):
+ end -= 1
+ return start, end
+ raise KeyError(ident)
+
+
+def mark_shipped(text, ident, release):
+ """The TOML with this item shipped in `release`, moved to the top of the shipped items (newest first)."""
+ lines = text.split("\n")
+ start, end = item_span(lines, ident)
+ block = [line for line in lines[start:end] if not line.startswith("shipped_in")]
+ block = [f'status = "shipped"\nshipped_in = "{release}"' if re.match(r"status\s*=", line) else line
+ for line in block]
+ block = [line for line in block if not re.match(r"focus\s*=", line)]
+ rest = lines[:start] + lines[end:]
+ # Drop the blank line the block leaves behind.
+ if start < len(rest) and start > 0 and not rest[start - 1].strip() and not rest[start].strip():
+ del rest[start]
+ shipped = [i for i, line in enumerate(rest) if re.match(r'status\s*=\s*"shipped"', line)]
+ if shipped:
+ header = max(i for i in range(shipped[0] + 1) if rest[i].strip() == "[[item]]")
+ rest[header:header] = block + [""]
+ else:
+ rest += [""] + block
+ return "\n".join(rest)
+
+
+def sync(data, text, states):
+ """Ship every item whose linked pull requests all went out in a release and whose linked issues are all
+ closed, unless it is ongoing. Returns the new text and what happened."""
+ log = []
+ for item in data.get("item", []):
+ if item.get("status") == "shipped":
+ continue
+ pulls = pull_requests(item, states)
+ # An ongoing item, or one with an open issue, still has work left whatever its pull requests say.
+ if item.get("ongoing") or open_issues(item, states):
+ continue
+ if not pulls or any(p["state"] != "MERGED" for p in pulls):
+ continue
+ release = release_of(pulls)
+ if release is None:
+ log.append(f"{item['id']}: merged, waiting for a release")
+ continue
+ text = mark_shipped(text, item["id"], release)
+ log.append(f"{item['id']}: shipped in {release}")
+ return text, log
+
+
+# --- labels ---------------------------------------------------------------------------------------------------
+
+def label_of(item):
+ """The GitHub label of an item: its name, colour and description (GitHub allows 100 characters)."""
+ description = f"Roadmap, {STATUSES[item['status']].lower()}: {item['title']}"
+ return {"name": LABEL_PREFIX + item["id"], "color": LABEL_COLOURS[item["status"]], "description": description[:100]}
+
+
+def label_changes(data, existing, states):
+ """What `labels` does: [(action, label or number, payload)] for labels to create or update, and open pull
+ requests linked from an item that lack its label. existing: {name: {"color", "description"}}; states as
+ github_states, plus each pull request's "labels"."""
+ changes = []
+ for item in data.get("item", []):
+ label = label_of(item)
+ have = existing.get(label["name"])
+ if have is None:
+ changes.append(("create", label["name"], label))
+ elif (have.get("color", "").lower(), have.get("description") or "") != (label["color"], label["description"]):
+ changes.append(("update", label["name"], label))
+ for link in item.get("links", []):
+ match = ISSUE.match(link)
+ state = states.get(int(match[1])) if match else None
+ if state and state["kind"] == "PullRequest" and state["state"] == "OPEN" and \
+ label["name"] not in state.get("labels", []):
+ changes.append(("add", int(match[1]), label["name"]))
+ stale = sorted(set(existing) - {LABEL_PREFIX + item["id"] for item in data.get("item", [])})
+ return changes, [name for name in stale if name.startswith(LABEL_PREFIX)]
+
+
+def github_rest(method, path, auth, body=None):
+ request = urllib.request.Request(
+ f"https://api.github.com{path}", method=method, data=None if body is None else json.dumps(body).encode(),
+ headers={"Authorization": f"bearer {auth}", "Accept": "application/vnd.github+json",
+ "User-Agent": "horizon-roadmap"})
+ with urllib.request.urlopen(request, timeout=30) as response:
+ return json.load(response) if response.status != 204 else None
+
+
+def existing_labels(auth):
+ labels, page = {}, 1
+ while True:
+ batch = github_rest("GET", f"/repos/{REPO}/labels?per_page=100&page={page}", auth)
+ labels.update({label["name"]: label for label in batch})
+ if len(batch) < 100:
+ return labels
+ page += 1
+
+
+# --- commands -------------------------------------------------------------------------------------------------
+
+def report(problems):
+ for problem in problems:
+ print(f"roadmap: {problem}", file=sys.stderr)
+ return 1 if problems else 0
+
+
+def command_build(args):
+ data = load()
+ problems = validate(data)
+ if problems:
+ return report(problems)
+ markdown = render(data)
+ if args.check:
+ if not OUTPUT.exists() or OUTPUT.read_text() != markdown:
+ return report(["ROADMAP.md is out of date: run `python3 tools/roadmap.py build`"])
+ return 0
+ OUTPUT.write_text(markdown)
+ print(f"roadmap: wrote {OUTPUT.relative_to(ROOT)}")
+ return 0
+
+
+def command_check(args):
+ data = load()
+ problems = validate(data)
+ if not problems and not args.offline:
+ states = github_states(numbers_in(data), token())
+ online, notes = online_problems(data, states, datetime.datetime.now(datetime.timezone.utc))
+ problems += online
+ for note in notes:
+ print(f"roadmap: {note}")
+ if not problems:
+ print(f"roadmap: {len(data.get('item', []))} items, all good")
+ return report(problems)
+
+
+def command_sync(args):
+ data = load()
+ problems = validate(data)
+ if problems:
+ return report(problems)
+ subprocess.run(["git", "fetch", "--quiet", "--tags", "origin"], cwd=ROOT, check=False)
+ text, log = sync(data, SOURCE.read_text(), github_states(numbers_in(data), token()))
+ for line in log:
+ print(f"roadmap: {line}")
+ if args.dry_run or text == SOURCE.read_text():
+ return 0
+ new = tomllib.loads(text)
+ if len(new.get("item", [])) != len(data.get("item", [])) or validate(new):
+ return report(["sync produced an invalid file; nothing written"] + validate(new))
+ SOURCE.write_text(text)
+ OUTPUT.write_text(render(new))
+ print("roadmap: wrote roadmap/roadmap.toml and ROADMAP.md")
+ return 0
+
+
+def command_labels(args):
+ data = load()
+ problems = validate(data)
+ if problems:
+ return report(problems)
+ auth = token()
+ changes, stale = label_changes(data, existing_labels(auth), github_states(numbers_in(data), auth))
+ for action, target, payload in changes:
+ print(f"roadmap: {action} {target}" + (f" ({payload})" if action == "add" else ""))
+ if args.dry_run:
+ continue
+ if action == "create":
+ github_rest("POST", f"/repos/{REPO}/labels", auth, payload)
+ elif action == "update":
+ github_rest("PATCH", f"/repos/{REPO}/labels/{urllib.parse.quote(target, safe='')}", auth,
+ {"color": payload["color"], "description": payload["description"]})
+ else:
+ github_rest("POST", f"/repos/{REPO}/issues/{target}/labels", auth, {"labels": [payload]})
+ for name in stale:
+ print(f"roadmap: {name} names no item any more: rename or delete it by hand (it stays on its pull requests)")
+ if not changes:
+ print("roadmap: labels up to date")
+ return 0
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ commands = parser.add_subparsers(dest="command", required=True)
+ build = commands.add_parser("build", help="write ROADMAP.md")
+ build.add_argument("--check", action="store_true", help="fail when ROADMAP.md is out of date")
+ check = commands.add_parser("check", help="the roadmap's rules, and GitHub's state of its links")
+ check.add_argument("--offline", action="store_true", help="skip GitHub")
+ sync_command = commands.add_parser("sync", help="ship the items whose pull requests all merged")
+ sync_command.add_argument("--dry-run", action="store_true", help="say what would change, write nothing")
+ labels = commands.add_parser("labels", help="a roadmap: label per item, on its linked open pull requests")
+ labels.add_argument("--dry-run", action="store_true", help="say what would change, change nothing")
+ args = parser.parse_args(argv)
+ return {"build": command_build, "check": command_check, "sync": command_sync,
+ "labels": command_labels}[args.command](args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
From 98bebd26bdc33efaa4483ac5d5cbb07250fc1345 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 15:14:48 +0100
Subject: [PATCH 29/88] Launcher: one place reads the pinned appearance
(theme::pinned_dark)
The title bar and the theme both resolved HORIZON_LAUNCHER_APPEARANCE and the
Settings choice; titlebar::apply_appearance now uses the theme's helper.
Co-Authored-By: Claude Opus 5.5
---
launcher/src/theme.rs | 39 +++++++++++++++++++++++++--------------
launcher/src/titlebar.rs | 21 +++++++--------------
2 files changed, 32 insertions(+), 28 deletions(-)
diff --git a/launcher/src/theme.rs b/launcher/src/theme.rs
index 60b796709..9d495a598 100644
--- a/launcher/src/theme.rs
+++ b/launcher/src/theme.rs
@@ -74,22 +74,33 @@ fn c(hex: u32) -> Hsla {
rgb(hex).into()
}
+/// Whether the launcher is pinned dark (`Some(true)`) or light, or follows the system (`None`):
+/// `HORIZON_LAUNCHER_APPEARANCE=light` or `dark` (for screenshots and tests), else the player's
+/// choice in Settings.
+pub fn pinned_dark(choice: Appearance) -> Option {
+ match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() {
+ Ok("light") => Some(false),
+ Ok("dark") => Some(true),
+ _ => match choice {
+ Appearance::Dark => Some(true),
+ Appearance::Light => Some(false),
+ Appearance::System => None,
+ },
+ }
+}
+
impl Theme {
- /// The player's choice in Settings (dark unless they picked another), the system's when they
- /// asked to follow it. `HORIZON_LAUNCHER_APPEARANCE=light` or `dark` overrides both (for
- /// screenshots and tests).
+ /// The pinned look (`pinned_dark`: dark unless the player picked another), the system's when
+ /// they asked to follow it.
pub fn for_appearance(choice: Appearance, system: WindowAppearance) -> Self {
- match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() {
- Ok("light") => return Self::light(),
- Ok("dark") => return Self::dark(),
- _ => {}
- }
- match (choice, system) {
- (Appearance::Light, _) => Self::light(),
- (Appearance::System, WindowAppearance::Light | WindowAppearance::VibrantLight) => {
- Self::light()
- }
- _ => Self::dark(),
+ let system_dark = !matches!(
+ system,
+ WindowAppearance::Light | WindowAppearance::VibrantLight
+ );
+ if pinned_dark(choice).unwrap_or(system_dark) {
+ Self::dark()
+ } else {
+ Self::light()
}
}
diff --git a/launcher/src/titlebar.rs b/launcher/src/titlebar.rs
index 2e6445091..a023f7d7d 100644
--- a/launcher/src/titlebar.rs
+++ b/launcher/src/titlebar.rs
@@ -22,9 +22,8 @@ pub fn render(_theme: &Theme, _window: &Window) -> Option {
/// macOS keeps the window's appearance on the system setting, so a launcher set to Dark still
/// draws a light title bar on a light desktop. Pin the NSWindow's appearance to the choice
-/// instead (`System` clears the pin, handing the chrome back to the system), honouring the same
-/// `HORIZON_LAUNCHER_APPEARANCE` override the theme does. Other platforms' chrome already
-/// follows the setting (ours is drawn, Windows and Linux follow the system either way).
+/// instead (`theme::pinned_dark`: `System` clears the pin, handing the chrome back to the
+/// system). Elsewhere the chrome is ours (Windows) or the system's (Linux).
#[cfg(target_os = "macos")]
pub fn apply_appearance(window: &Window, choice: Appearance) {
use objc2_app_kit::{
@@ -33,17 +32,11 @@ pub fn apply_appearance(window: &Window, choice: Appearance) {
};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
- // Reading AppKit's name constants is unsafe to rustc only (`use of extern static`).
- let name: Option<&'static NSAppearanceName> = unsafe {
- match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() {
- Ok("light") => Some(NSAppearanceNameAqua),
- Ok("dark") => Some(NSAppearanceNameDarkAqua),
- _ => match choice {
- Appearance::Dark => Some(NSAppearanceNameDarkAqua),
- Appearance::Light => Some(NSAppearanceNameAqua),
- Appearance::System => None,
- },
- }
+ // AppKit's name constants are extern statics: reading them is `unsafe` to rustc only.
+ let name: Option<&'static NSAppearanceName> = match crate::theme::pinned_dark(choice) {
+ Some(true) => Some(unsafe { NSAppearanceNameDarkAqua }),
+ Some(false) => Some(unsafe { NSAppearanceNameAqua }),
+ None => None,
};
// The trait, not `Window::window_handle` (which is gpui's own `AnyWindowHandle`).
let Ok(handle) = HasWindowHandle::window_handle(window) else {
From 6d418fdb3ef91907ee71f055991b88294d479efa Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Sun, 25 Oct 2026 15:17:19 +0100
Subject: [PATCH 30/88] Docs: publish a mod through the registry, and how
horizon-mods runs
docs/mods.md gets "Publish your mod" (the form, the review, updates) and
its Distribution section points at the registry instead of the plan for
it. docs/api/mod-index.md says how horizon-mods runs: its checks, merging,
Pages, the weekly cleanup, and that removing an entry needs an admin merge
(takedowns go in revoked.toml). The service's README says where it runs on
Railway.
Co-Authored-By: Claude Opus 5.5
---
crates/horizon-mod-registry/README.md | 7 ++++--
docs/api/mod-index.md | 17 +++++++++++++-
docs/mods.md | 33 ++++++++++++++++++++++-----
3 files changed, 48 insertions(+), 9 deletions(-)
diff --git a/crates/horizon-mod-registry/README.md b/crates/horizon-mod-registry/README.md
index 936fe5acf..f7cdc68c5 100644
--- a/crates/horizon-mod-registry/README.md
+++ b/crates/horizon-mod-registry/README.md
@@ -40,5 +40,8 @@ REGISTRY_PUBLIC_URL=http://localhost:4173 REGISTRY_SESSION_KEY=... GITHUB_CLIENT
| `REGISTRY_REPO` | Default `ludovic111/horizon-mods` |
| `PORT` | Default 8080 |
-On Railway it is its own service (`railway.json`, built with the `Dockerfile` from the repository root); the website's
-Caddy sends `/api/mods/*` to it over Railway's private network.
+On Railway it is the service `horizon-mod-registry` of the project `horizon-site`, next to the website: built from
+`main` with this `Dockerfile` from the repository root, health check `/healthz`, no public domain and no volume. The
+website's Caddy sends `/api/mods/*` to it over Railway's private network (`REGISTRY_UPSTREAM` on the website service:
+`http://horizon-mod-registry.railway.internal:8080`). `railway.json` lists the same settings; Railway reads them from
+the service, not from the file.
diff --git a/docs/api/mod-index.md b/docs/api/mod-index.md
index beb6ec2c8..6b807d950 100644
--- a/docs/api/mod-index.md
+++ b/docs/api/mod-index.md
@@ -138,9 +138,24 @@ Unknown keys are refused. Its CI runs `cargo-horizon-mod` (`crates/cargo-horizon
| `cargo horizon-mod check [--json]` | A submission's checks: its kind's (above), its signature with `--key` and `--signature`, and for a mod a trial run in the sandbox (40 ticks, 120 frames, a chat line, each command). |
| `cargo horizon-mod registry check --files ` | `check` on each file `head` lists and `base` doesn't: a pull request's new files. |
| `cargo horizon-mod registry list ` | ` ` per version: the files to download. |
-| `cargo horizon-mod registry build --files --out index.json` | Reads every entry and its file (`/`), lists every problem, and writes the index with URLs `/-/`. |
+| `cargo horizon-mod registry build --files