Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.
Rust differential-testinggame-enginegamedevlinuxminecraftminecraft-javareimplementationrustvoxelvulkanwgpu
//! The launcher's generated executable for trait mods.
use super::{Bundle, MANIFEST};
use std::fs;
use std::path::Path;
/// Match horizon-mixins crate IDs before using them as folder names.
pub(super) fn valid_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 100
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
fn read(path: &Path) -> Result<toml::Table, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
text.parse().map_err(|e| format!("{}: {e}", path.display()))
}
fn write(path: &Path, value: &toml::Table) -> Result<(), String> {
let text = toml::to_string(value).map_err(|e| format!("{}: {e}", path.display()))?;
fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}
/// Remove launcher-only tables from the incoming copy before horizon-mixins reads it.
pub(super) fn strip(bundle: &Bundle) -> Result<(), String> {
let path = bundle.dir.join(MANIFEST);
let mut manifest = read(&path)?;
let api = manifest.remove("api");
let dependencies = manifest.remove("dependencies");
if api.is_some() || dependencies.is_some() {
write(&path, &manifest)?;
}
Ok(())
}
/// Read and validate the trait package folder at the manifest boundary.
pub(super) fn folder(dir: &Path, table: &toml::Value) -> Result<String, String> {
let manifest = dir.join(MANIFEST);
if !table
.as_table()
.is_some_and(|t| t.len() == 1 && t.contains_key("path"))
{
return Err(format!("{}: [api] accepts only path", manifest.display()));
}
let folder = table
.get("path")
.and_then(toml::Value::as_str)
.ok_or_else(|| format!("{}: [api] needs a path", manifest.display()))?;
let relative = Path::new(folder);
// An absolute path would bypass the incoming copy when joined later.
if relative.is_absolute() {
return Err(format!(
"{}: invalid [api] path {folder:?}",
manifest.display()
));
}
let source = dir.join(relative);
let root = dir
.canonicalize()
.map_err(|e| format!("{}: {e}", dir.display()))?;
let resolved = source
.canonicalize()
.map_err(|e| format!("{}: {e}", source.display()))?;
if !resolved.starts_with(&root) || !resolved.join("Cargo.toml").is_file() {
return Err(format!(
"{}: [api] path must be a folder in the bundle with Cargo.toml",
manifest.display()
));
}
Ok(folder.to_owned())
}
pub(super) const PACKAGE: &str = "horizon-native-game";
/// Where the generated executable's package is staged, in the workspace.
const GAME: &str = "crates/native-game";
fn path_dep(path: &str) -> toml::Value {
toml::Value::Table(toml::Table::from_iter([("path".into(), path.into())]))
}
fn main_rs(count: usize) -> String {
let entries = (0..count)
.map(|i| format!(" mod_{i}::hooks(),\n"))
.collect::<String>();
// Mirrors crates/horizon-client/src/main.rs, with trait mods passed to main_with.
format!(
r#"//! Generated by the launcher.
#![forbid(unsafe_code)]
#[global_allocator]
static ALLOCATOR: horizon_threads::Allocator = horizon_threads::Allocator;
static MOD_API_LEVEL: [u8; horizon_mods::api_level::MARK.len()] = horizon_mods::api_level::MARK;
fn main() {{
std::hint::black_box(&MOD_API_LEVEL);
let mods: horizon_client::mod_api::Mods = vec![
{entries} ].into();
horizon_client::entry::main_with(mods);
}}
"#
)
}
/// API objects in the same order as the generated executable's mod list.
pub(super) fn with_api(mods: &[Bundle]) -> impl Iterator<Item = &Bundle> {
mods.iter().filter(|m| m.api.is_some())
}
/// Add API packages and the generated executable to the fresh staged workspace.
pub(super) fn stage(
stage: &Path,
bundles: &[Bundle],
declared: &[Vec<super::dependencies::Dependency>],
resolution: &super::dependencies::Resolution,
) -> Result<bool, String> {
let mods: Vec<_> = resolution
.order
.iter()
.map(|&i| (i, &bundles[i]))
.filter(|(_, b)| b.api.is_some())
.collect();
let mut packages = std::collections::HashMap::new();
for (_, bundle) in &mods {
let path = bundle
.dir
.join(bundle.api.as_ref().expect("filtered"))
.join("Cargo.toml");
let manifest = read(&path)?;
let name = manifest
.get("package")
.and_then(|p| p.get("name"))
.and_then(toml::Value::as_str)
.ok_or_else(|| format!("{}: missing package name", path.display()))?;
packages.insert(bundle.id.as_str(), name.to_owned());
}
if mods.is_empty() {
return Ok(false);
}
let mut deps = toml::Table::new();
for name in ["horizon-client", "horizon-threads", "horizon-mods"] {
deps.insert(name.into(), path_dep(&format!("../{name}")));
}
// horizon-client's defaults (sound, controllers) are this package's, so a server build's
// `--no-default-features` turns them off here too.
if let Some(client) = deps
.get_mut("horizon-client")
.and_then(toml::Value::as_table_mut)
{
client.insert("default-features".into(), false.into());
}
let mut members = Vec::new();
for (i, (index, bundle)) in mods.iter().enumerate() {
let relative = format!("native-api/{}", bundle.id);
let dest = stage.join(&relative);
let source = bundle.dir.join(bundle.api.as_ref().expect("filtered"));
super::sync(&source, &dest)?;
let path = dest.join("Cargo.toml");
let mut manifest = read(&path)?;
let package = manifest
.get("package")
.and_then(|p| p.get("name"))
.and_then(toml::Value::as_str)
.ok_or_else(|| format!("{}: missing package name", path.display()))?
.to_owned();
let dependencies = manifest
.get_mut("dependencies")
.and_then(toml::Value::as_table_mut)
.ok_or_else(|| format!("{}: missing horizon-client dependency", path.display()))?;
let dependency = dependencies
.iter_mut()
.find(|(key, value)| {
*key == "horizon-client"
|| value.get("package").and_then(toml::Value::as_str) == Some("horizon-client")
})
.ok_or_else(|| format!("{}: missing horizon-client dependency", path.display()))?
.1;
let mut rewritten = path_dep("../../crates/horizon-client");
if let (Some(old), Some(new)) = (dependency.as_table(), rewritten.as_table_mut()) {
// A renamed dependency also needs its package name.
for key in ["package", "features", "default-features"] {
if let Some(value) = old.get(key) {
new.insert(key.into(), value.clone());
}
}
}
// The game's features are the generated package's to choose (a server build turns its
// defaults off), so no mod turns them back on.
if let Some(new) = rewritten.as_table_mut() {
new.insert("default-features".into(), false.into());
}
*dependency = rewritten;
let targets: Vec<_> = declared[*index]
.iter()
.map(|dependency| super::dependencies::Package {
dependency,
package: packages.get(dependency.id.as_str()).map(String::as_str),
})
.collect();
let enabled = super::dependencies::rewrite(&bundle.id, &mut manifest, &targets)
.map_err(|e| e.to_string())?;
write(&path, &manifest)?;
let mut dep = toml::Table::new();
dep.insert("path".into(), format!("../../{relative}").into());
dep.insert("package".into(), package.into());
if !enabled.is_empty() {
dep.insert(
"features".into(),
toml::Value::Array(enabled.into_iter().map(toml::Value::String).collect()),
);
}
deps.insert(format!("mod_{i}"), toml::Value::Table(dep));
members.push(relative);
}
// Beside horizon-client, so its build script (the Windows stack size and icon, for the
// `horizon-client` binary this package owns now) finds `packaging/` where it looks.
let game = stage.join(GAME);
fs::create_dir_all(game.join("src")).map_err(|e| e.to_string())?;
let mut manifest = toml::Table::new();
manifest.insert(
"package".into(),
toml::Value::Table(toml::Table::from_iter([
("name".into(), PACKAGE.into()),
("version".into(), "0.1.0".into()),
("edition".into(), "2024".into()),
("publish".into(), false.into()),
("build".into(), "../horizon-client/build.rs".into()),
])),
);
let windows = toml::Table::from_iter([(
"build-dependencies".into(),
toml::Value::Table(toml::Table::from_iter([(
"winresource".into(),
"0.1".into(),
)])),
)]);
manifest.insert(
"target".into(),
toml::Value::Table(toml::Table::from_iter([(
"cfg(windows)".into(),
toml::Value::Table(windows),
)])),
);
manifest.insert(
"bin".into(),
toml::Value::Array(vec![toml::Value::Table(toml::Table::from_iter([
("name".into(), "horizon-client".into()),
("path".into(), "src/main.rs".into()),
]))]),
);
manifest.insert("dependencies".into(), toml::Value::Table(deps));
manifest.insert(
"features".into(),
toml::Value::Table(toml::Table::from_iter([(
"default".into(),
toml::Value::Array(vec!["horizon-client/default".into()]),
)])),
);
write(&game.join("Cargo.toml"), &manifest)?;
fs::write(game.join("src/main.rs"), main_rs(mods.len())).map_err(|e| e.to_string())?;
let root = stage.join("Cargo.toml");
let mut workspace = read(&root)?;
let list = workspace
.get_mut("workspace")
.and_then(|w| w.get_mut("members"))
.and_then(toml::Value::as_array_mut)
.ok_or("workspace has no members")?;
members.push(GAME.into());
list.extend(members.into_iter().map(toml::Value::String));
write(&root, &workspace)?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(manifest: &str) -> std::path::PathBuf {
let name = std::thread::current().name().unwrap().replace(':', "-");
let dir = super::super::tests::dir(&name);
fs::create_dir_all(dir.join("engine/src")).unwrap();
fs::write(dir.join(MANIFEST), manifest).unwrap();
fs::write(dir.join("engine/Cargo.toml"), "[package]\nname = 'example-mod'\nversion = '0.1.0'\nedition = '2024'\n[dependencies]\nhorizon-client = '0.1'\n").unwrap();
fs::write(dir.join("engine/src/lib.rs"), "").unwrap();
dir
}
#[test]
fn validates_the_api_folder() {
for (path, valid) in [
("engine", true),
("missing", false),
("../engine", false),
("/engine", false),
] {
let dir = fixture(&format!(
"[mod]\nid = 'example'\nversion = '1'\n[api]\npath = {path:?}\n"
));
assert_eq!(super::super::bundle(&dir, None).is_ok(), valid, "{path}");
fs::remove_dir_all(dir).unwrap();
}
}
#[test]
fn rejects_an_entry_override() {
let dir = fixture(
"[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\nentry = 'other'\n",
);
assert!(super::super::bundle(&dir, None)
.unwrap_err()
.contains("accepts only path"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn removes_only_the_api_table_for_mixins() {
let dir = fixture(
"[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n[dependencies]\nbase = '^1'\n[[injection]]\nid = 'test'\n",
);
let bundle = super::super::bundle(&dir, None).unwrap();
assert!(bundle.mixins_content);
strip(&bundle).unwrap();
let value = read(&dir.join(MANIFEST)).unwrap();
assert!(!value.contains_key("api"));
assert!(!value.contains_key("dependencies"));
assert!(value.contains_key("injection"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn generated_main_keeps_mod_order() {
for count in 0..=2 {
let text = main_rs(count);
assert!(text.contains("entry::main_with(mods)"));
assert_eq!(text.matches("::hooks()").count(), count);
if count == 2 {
assert!(
text.find("mod_0::hooks()").unwrap() < text.find("mod_1::hooks()").unwrap()
);
}
}
}
#[test]
fn stages_api_without_a_dependency_cycle() {
let dir = fixture("[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n");
let bundle = super::super::bundle(&dir, None).unwrap();
let stage_dir = dir.join("workspace");
fs::create_dir_all(&stage_dir).unwrap();
fs::write(stage_dir.join("Cargo.toml"), "[workspace]\nmembers = []\n").unwrap();
let resolution = super::super::dependencies::Resolution { order: vec![0] };
assert!(stage(&stage_dir, &[bundle], &[vec![]], &resolution).unwrap());
let root = read(&stage_dir.join("Cargo.toml")).unwrap();
let members = root["workspace"]["members"].as_array().unwrap();
assert!(members
.iter()
.any(|v| v.as_str() == Some("native-api/example")));
assert!(members.iter().any(|v| v.as_str() == Some(GAME)));
let engine = read(&stage_dir.join("native-api/example/Cargo.toml")).unwrap();
assert_eq!(
engine["dependencies"]["horizon-client"]["path"].as_str(),
Some("../../crates/horizon-client")
);
let game = read(&stage_dir.join(GAME).join("Cargo.toml")).unwrap();
assert_eq!(
game["dependencies"]["mod_0"]["package"].as_str(),
Some("example-mod")
);
assert_eq!(
game["dependencies"]["mod_0"]["path"].as_str(),
Some("../../native-api/example")
);
assert_eq!(
game["package"]["build"].as_str(),
Some("../horizon-client/build.rs")
);
assert!(stage_dir
.join(GAME)
.join(
game["dependencies"]["horizon-client"]["path"]
.as_str()
.unwrap()
)
.ends_with("crates/native-game/../horizon-client"));
// The game's default features are the generated package's alone, so a server build's
// `--no-default-features` reaches horizon-client.
assert_eq!(
engine["dependencies"]["horizon-client"]["default-features"].as_bool(),
Some(false)
);
assert_eq!(
game["dependencies"]["horizon-client"]["default-features"].as_bool(),
Some(false)
);
assert_eq!(
game["features"]["default"][0].as_str(),
Some("horizon-client/default")
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn api_only_skips_mixins() {
let dir = fixture("[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n");
let bundle = super::super::bundle(&dir, None).unwrap();
assert!(!bundle.mixins_content);
fs::remove_dir_all(dir).unwrap();
}
}