horizon-mods: content mods (API 0.2), blocks and items declared from vanilla templates
A .hmod may carry assets/ and data/ beside mod.wasm, or instead of it. The
manifest needs api = "0.2" and the new registries capability ("add blocks
and items to your worlds"). Content mods have no WIT interface: code still
links API 0.1.
horizon_mods::content::Content reads a mod's content and checks it:
- plain resource paths only;
- 65,536 files, 16 MiB each, 512 MiB in all;
- files in the mod's own namespace, plus additions to vanilla tags;
- blocks and items declared in data/<id>/horizon/{block,item}/*.json, each
copying a vanilla template with typed overrides (hardness, resistance,
light, tool, friction, map colour, sounds; stack size, rarity), unknown
keys refused.
Mods::load refuses an enabled mod whose content fails these checks, with
the reason on its row. A content-only mod is on with no engine and no hooks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+1
@@ -1483,6 +1483,7 @@ dependencies = [
|
||||
"horizon-mods",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
"wasmtime",
|
||||
"wit-component 0.239.0",
|
||||
|
||||
@@ -8,6 +8,7 @@ description = "Horizon's mod runtime: sandboxed WebAssembly components (docs/mod
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
toml = "1.1.6"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
log = "0.4"
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
//! A content mod's `assets/` and `data/` (API 0.2, docs/modpacks.md): the
|
||||
//! files it adds to the game's resource tree, and the blocks and items it
|
||||
//! declares in `data/<id>/horizon/block/` and `data/<id>/horizon/item/`.
|
||||
//!
|
||||
//! Content is data, not code: nothing here runs in the sandbox. What a mod
|
||||
//! may add is fenced instead. Its own namespace, plus additions to vanilla
|
||||
//! tags. Paths are plain, files and totals are capped, and vanilla ids
|
||||
//! cannot be redefined.
|
||||
use crate::manifest::{Capability, MANIFEST, Manifest};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
io::Read,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// Content files per mod, bytes per file and bytes per mod.
|
||||
pub const MAX_FILES: usize = 65_536;
|
||||
pub const MAX_FILE: u64 = 16 << 20;
|
||||
pub const MAX_TOTAL: u64 = 512 << 20;
|
||||
|
||||
/// Checks a content path: `assets/` or `data/`, then `/`-separated parts of
|
||||
/// `[a-z0-9_.-]`, none of them `.` or `..` (vanilla's resource-location
|
||||
/// characters, so the path means the same on every OS).
|
||||
pub fn check_path(name: &str) -> Result<(), String> {
|
||||
let bad = || format!("{name:?} is not a plain assets/ or data/ path");
|
||||
let mut parts = name.split('/');
|
||||
if !matches!(parts.next(), Some("assets" | "data")) {
|
||||
return Err(bad());
|
||||
}
|
||||
let mut count = 0;
|
||||
for part in parts {
|
||||
count += 1;
|
||||
let chars_ok = part
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-".contains(&b));
|
||||
if part.is_empty() || part == "." || part == ".." || !chars_ok {
|
||||
return Err(bad());
|
||||
}
|
||||
}
|
||||
// assets/<namespace>/<file> at least.
|
||||
if count < 2 {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A vanilla identifier, `minecraft:path`.
|
||||
fn vanilla_id(id: &str) -> bool {
|
||||
id.strip_prefix("minecraft:").is_some_and(|path| {
|
||||
!path.is_empty()
|
||||
&& path
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_./-".contains(&b))
|
||||
})
|
||||
}
|
||||
|
||||
/// What a declared block changes from its template; unset keeps the
|
||||
/// template's value.
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BlockProperties {
|
||||
/// Destroy time in seconds of hand mining (-1: unbreakable).
|
||||
pub hardness: Option<f32>,
|
||||
pub explosion_resistance: Option<f32>,
|
||||
/// Light emitted, 0 to 15.
|
||||
pub light: Option<u8>,
|
||||
pub requires_tool: Option<bool>,
|
||||
pub friction: Option<f32>,
|
||||
/// A `MapColor` id, 0 to 61.
|
||||
pub map_color: Option<u8>,
|
||||
/// A vanilla block whose sounds this block uses.
|
||||
pub sounds: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct BlockFile {
|
||||
template: String,
|
||||
#[serde(default)]
|
||||
properties: BlockProperties,
|
||||
#[serde(default = "yes")]
|
||||
item: bool,
|
||||
}
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// A block the mod adds: a vanilla template's behaviour, states and shapes
|
||||
/// under a new id, with `properties` applied.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Block {
|
||||
/// `<mod id>:<path>`.
|
||||
pub id: String,
|
||||
/// The vanilla block it copies, `minecraft:<path>`.
|
||||
pub template: String,
|
||||
pub properties: BlockProperties,
|
||||
/// Also add a block item with the same id.
|
||||
pub item: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Rarity {
|
||||
Common,
|
||||
Uncommon,
|
||||
Rare,
|
||||
Epic,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ItemFile {
|
||||
template: String,
|
||||
max_stack_size: Option<u8>,
|
||||
rarity: Option<Rarity>,
|
||||
}
|
||||
|
||||
/// An item the mod adds: a vanilla template item's components under a new
|
||||
/// id, with these changed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Item {
|
||||
pub id: String,
|
||||
/// The vanilla item it copies, `minecraft:<path>`.
|
||||
pub template: String,
|
||||
pub max_stack_size: Option<u8>,
|
||||
pub rarity: Option<Rarity>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Source {
|
||||
Dir(PathBuf),
|
||||
Zip(PathBuf),
|
||||
}
|
||||
|
||||
/// A mod's content: its files and declarations.
|
||||
#[derive(Debug)]
|
||||
pub struct Content {
|
||||
source: Source,
|
||||
/// Every content file (`assets/...`, `data/...`), sorted.
|
||||
pub files: Vec<String>,
|
||||
pub blocks: Vec<Block>,
|
||||
pub items: Vec<Item>,
|
||||
}
|
||||
|
||||
impl Content {
|
||||
/// The content of the mod at `path` (a `.hmod` or a mod folder).
|
||||
pub fn read(path: &Path, manifest: &Manifest) -> Result<Content, String> {
|
||||
let (source, sized) = if path.is_dir() {
|
||||
let mut out = Vec::new();
|
||||
for top in ["assets", "data"] {
|
||||
walk(path, &path.join(top), &mut out)?;
|
||||
}
|
||||
(Source::Dir(path.to_owned()), out)
|
||||
} else {
|
||||
let mut zip = open_zip(path)?;
|
||||
let mut out = Vec::new();
|
||||
for i in 0..zip.len() {
|
||||
let entry = zip.by_index_raw(i).map_err(|e| e.to_string())?;
|
||||
let name = entry.name();
|
||||
if (name.starts_with("assets/") || name.starts_with("data/")) && !entry.is_dir() {
|
||||
out.push((name.to_owned(), entry.size()));
|
||||
}
|
||||
}
|
||||
(Source::Zip(path.to_owned()), out)
|
||||
};
|
||||
let mut files = Vec::with_capacity(sized.len());
|
||||
let mut total = 0u64;
|
||||
for (name, size) in sized {
|
||||
check_path(&name)?;
|
||||
if size > MAX_FILE {
|
||||
return Err(format!("{name} is over {} MiB", MAX_FILE >> 20));
|
||||
}
|
||||
total += size;
|
||||
files.push(name);
|
||||
}
|
||||
if files.len() > MAX_FILES {
|
||||
return Err(format!("more than {MAX_FILES} content files"));
|
||||
}
|
||||
if total > MAX_TOTAL {
|
||||
return Err(format!("content is over {} MiB", MAX_TOTAL >> 20));
|
||||
}
|
||||
files.sort();
|
||||
files.dedup();
|
||||
let mut content = Content {
|
||||
source,
|
||||
files,
|
||||
blocks: Vec::new(),
|
||||
items: Vec::new(),
|
||||
};
|
||||
content.check(manifest)?;
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// No files: a mod with code only.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.files.is_empty()
|
||||
}
|
||||
|
||||
/// One content file's bytes.
|
||||
pub fn file(&self, name: &str) -> Result<Vec<u8>, String> {
|
||||
check_path(name)?;
|
||||
let mut out = Vec::new();
|
||||
match &self.source {
|
||||
Source::Dir(root) => {
|
||||
let file =
|
||||
std::fs::File::open(root.join(name)).map_err(|e| format!("{name}: {e}"))?;
|
||||
file.take(MAX_FILE + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("{name}: {e}"))?;
|
||||
}
|
||||
Source::Zip(path) => {
|
||||
let mut zip = open_zip(path)?;
|
||||
let entry = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
|
||||
entry
|
||||
.take(MAX_FILE + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("{name}: {e}"))?;
|
||||
}
|
||||
}
|
||||
if out.len() as u64 > MAX_FILE {
|
||||
return Err(format!("{name} is over {} MiB", MAX_FILE >> 20));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where content may go, and the declarations.
|
||||
fn check(&mut self, manifest: &Manifest) -> Result<(), String> {
|
||||
let id = manifest.id.as_str();
|
||||
if !self.files.is_empty() && !manifest.capabilities.contains(&Capability::Registries) {
|
||||
return Err(format!(
|
||||
"has assets/ or data/ but not capability registries in {MANIFEST}"
|
||||
));
|
||||
}
|
||||
let mut blocks = Vec::new();
|
||||
let mut items = Vec::new();
|
||||
for name in &self.files {
|
||||
let mut parts = name.splitn(3, '/');
|
||||
let (top, namespace, rest) = (
|
||||
parts.next().unwrap_or(""),
|
||||
parts.next().unwrap_or(""),
|
||||
parts.next().unwrap_or(""),
|
||||
);
|
||||
let own = namespace == id;
|
||||
// Vanilla's own files stay vanilla's; a mod may only add to its tags.
|
||||
let allowed =
|
||||
own || (top == "data" && namespace == "minecraft" && rest.starts_with("tags/"));
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla tags"
|
||||
));
|
||||
}
|
||||
let Some(decl) = (own && top == "data")
|
||||
.then(|| rest.strip_prefix("horizon/"))
|
||||
.flatten()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let parse = |kind: &str| -> Option<String> {
|
||||
let path = decl
|
||||
.strip_prefix(kind)?
|
||||
.strip_prefix('/')?
|
||||
.strip_suffix(".json")?;
|
||||
Some(format!("{id}:{path}"))
|
||||
};
|
||||
if let Some(block) = parse("block") {
|
||||
blocks.push((block, name.clone()));
|
||||
} else if let Some(item) = parse("item") {
|
||||
items.push((item, name.clone()));
|
||||
} else {
|
||||
return Err(format!(
|
||||
"{name}: data/{id}/horizon/ holds block/*.json and item/*.json only"
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
for (block, name) in blocks {
|
||||
let file: BlockFile =
|
||||
serde_json::from_slice(&self.file(&name)?).map_err(|e| format!("{name}: {e}"))?;
|
||||
check_block(&file).map_err(|e| format!("{name}: {e}"))?;
|
||||
if file.item {
|
||||
ids.insert(block.clone());
|
||||
}
|
||||
self.blocks.push(Block {
|
||||
id: block,
|
||||
template: file.template,
|
||||
properties: file.properties,
|
||||
item: file.item,
|
||||
});
|
||||
}
|
||||
for (item, name) in items {
|
||||
let file: ItemFile =
|
||||
serde_json::from_slice(&self.file(&name)?).map_err(|e| format!("{name}: {e}"))?;
|
||||
if !vanilla_id(&file.template) {
|
||||
return Err(format!(
|
||||
"{name}: template {:?} is not a vanilla item (minecraft:...)",
|
||||
file.template
|
||||
));
|
||||
}
|
||||
if file.max_stack_size.is_some_and(|n| !(1..=99).contains(&n)) {
|
||||
return Err(format!("{name}: max_stack_size is 1 to 99"));
|
||||
}
|
||||
if !ids.insert(item.clone()) {
|
||||
return Err(format!("{name}: {item} is also a block's item"));
|
||||
}
|
||||
self.items.push(Item {
|
||||
id: item,
|
||||
template: file.template,
|
||||
max_stack_size: file.max_stack_size,
|
||||
rarity: file.rarity,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn check_block(file: &BlockFile) -> Result<(), String> {
|
||||
if !vanilla_id(&file.template) {
|
||||
return Err(format!(
|
||||
"template {:?} is not a vanilla block (minecraft:...)",
|
||||
file.template
|
||||
));
|
||||
}
|
||||
let p = &file.properties;
|
||||
let finite = |v: Option<f32>| v.is_none_or(f32::is_finite);
|
||||
if !finite(p.hardness) || !finite(p.explosion_resistance) || !finite(p.friction) {
|
||||
return Err("hardness, explosion_resistance and friction are numbers".into());
|
||||
}
|
||||
if p.hardness.is_some_and(|h| h < 0.0 && h != -1.0) {
|
||||
return Err("hardness is 0 or more, or -1 (unbreakable)".into());
|
||||
}
|
||||
if p.explosion_resistance.is_some_and(|r| r < 0.0) {
|
||||
return Err("explosion_resistance is 0 or more".into());
|
||||
}
|
||||
if p.friction.is_some_and(|f| !(0.0..=2.0).contains(&f)) {
|
||||
return Err("friction is 0 to 2".into());
|
||||
}
|
||||
if p.light.is_some_and(|l| l > 15) {
|
||||
return Err("light is 0 to 15".into());
|
||||
}
|
||||
if p.map_color.is_some_and(|c| c > 61) {
|
||||
return Err("map_color is a MapColor id, 0 to 61".into());
|
||||
}
|
||||
if p.sounds.as_deref().is_some_and(|s| !vanilla_id(s)) {
|
||||
return Err("sounds names a vanilla block (minecraft:...)".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_zip(path: &Path) -> Result<zip::ZipArchive<std::fs::File>, String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
zip::ZipArchive::new(file).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Files under `dir`, relative to `root` with `/` separators. Symbolic links
|
||||
/// are not followed: a mod folder holds its own files.
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, u64)>) -> Result<(), String> {
|
||||
let Ok(read) = std::fs::read_dir(dir) else {
|
||||
return Ok(());
|
||||
};
|
||||
for entry in read.flatten() {
|
||||
let path = entry.path();
|
||||
let meta = std::fs::symlink_metadata(&path).map_err(|e| e.to_string())?;
|
||||
if meta.is_dir() {
|
||||
walk(root, &path, out)?;
|
||||
} else if meta.is_file() {
|
||||
let rel = path.strip_prefix(root).map_err(|e| e.to_string())?;
|
||||
let parts: Option<Vec<&str>> = rel.iter().map(|p| p.to_str()).collect();
|
||||
let name = parts.ok_or_else(|| format!("{} is not UTF-8", rel.display()))?;
|
||||
out.push((name.join("/"), meta.len()));
|
||||
}
|
||||
if out.len() > MAX_FILES {
|
||||
return Err(format!("more than {MAX_FILES} content files"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::manifest::Package;
|
||||
|
||||
const MANIFEST_TEXT: &str = r#"
|
||||
id = "ruby"
|
||||
name = "Ruby"
|
||||
version = "0.1.0"
|
||||
api = "0.2"
|
||||
side = "both"
|
||||
capabilities = ["registries"]
|
||||
"#;
|
||||
const BLOCK: &[u8] = br#"{"template": "minecraft:iron_block",
|
||||
"properties": {"hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block"}}"#;
|
||||
const ITEM: &[u8] = br#"{"template": "minecraft:diamond", "rarity": "uncommon"}"#;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("horizon-content-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
fn hmod(name: &str, manifest: &str, files: &[(&str, &[u8])]) -> Result<Content, String> {
|
||||
let dir = scratch(name);
|
||||
let path = dir.join("m.hmod");
|
||||
std::fs::write(&path, Package::write_files(manifest, None, files)?).unwrap();
|
||||
let package = Package::read(&path);
|
||||
let content = package.and_then(|p| Content::read(&path, &p.manifest));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
content
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_mod_round_trips() {
|
||||
let files: &[(&str, &[u8])] = &[
|
||||
("data/ruby/horizon/block/ruby_block.json", BLOCK),
|
||||
("data/ruby/horizon/item/ruby.json", ITEM),
|
||||
("data/ruby/recipe/ruby_block.json", b"{}"),
|
||||
("data/minecraft/tags/block/mineable/pickaxe.json", b"{}"),
|
||||
("assets/ruby/textures/block/ruby_block.png", b"png"),
|
||||
];
|
||||
let content = hmod("ok", MANIFEST_TEXT, files).unwrap();
|
||||
assert_eq!(content.files.len(), 5);
|
||||
assert_eq!(
|
||||
content.blocks,
|
||||
[Block {
|
||||
id: "ruby:ruby_block".into(),
|
||||
template: "minecraft:iron_block".into(),
|
||||
properties: BlockProperties {
|
||||
hardness: Some(4.0),
|
||||
light: Some(3),
|
||||
sounds: Some("minecraft:amethyst_block".into()),
|
||||
..BlockProperties::default()
|
||||
},
|
||||
item: true,
|
||||
}]
|
||||
);
|
||||
assert_eq!(content.items[0].id, "ruby:ruby");
|
||||
assert_eq!(content.items[0].rarity, Some(Rarity::Uncommon));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_mod_reads_the_same() {
|
||||
let dir = scratch("folder");
|
||||
std::fs::write(dir.join(MANIFEST), MANIFEST_TEXT).unwrap();
|
||||
let block = dir.join("data/ruby/horizon/block");
|
||||
std::fs::create_dir_all(&block).unwrap();
|
||||
std::fs::write(block.join("ruby_block.json"), BLOCK).unwrap();
|
||||
let package = Package::read(&dir).unwrap();
|
||||
assert!(package.wasm.is_none());
|
||||
let content = Content::read(&dir, &package.manifest).unwrap();
|
||||
assert_eq!(content.files, ["data/ruby/horizon/block/ruby_block.json"]);
|
||||
assert_eq!(content.file(&content.files[0]).unwrap(), BLOCK);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_content_outside_its_fence() {
|
||||
let refused = |name: &str, files: &[(&str, &[u8])]| {
|
||||
let e = hmod(name, MANIFEST_TEXT, files).unwrap_err();
|
||||
assert!(!e.is_empty());
|
||||
e
|
||||
};
|
||||
let e = refused("other-ns", &[("data/other/horizon/block/a.json", BLOCK)]);
|
||||
assert!(e.contains("own namespace"), "{e}");
|
||||
refused(
|
||||
"vanilla-asset",
|
||||
&[("assets/minecraft/textures/block/stone.png", b"x")],
|
||||
);
|
||||
refused(
|
||||
"vanilla-recipe",
|
||||
&[("data/minecraft/recipe/stone.json", b"{}")],
|
||||
);
|
||||
let e = refused(
|
||||
"modded-template",
|
||||
&[(
|
||||
"data/ruby/horizon/block/a.json",
|
||||
br#"{"template": "ruby:other"}"#,
|
||||
)],
|
||||
);
|
||||
assert!(e.contains("not a vanilla block"), "{e}");
|
||||
refused(
|
||||
"light",
|
||||
&[(
|
||||
"data/ruby/horizon/block/a.json",
|
||||
br#"{"template": "minecraft:stone", "properties": {"light": 16}}"#,
|
||||
)],
|
||||
);
|
||||
refused(
|
||||
"unknown-key",
|
||||
&[(
|
||||
"data/ruby/horizon/block/a.json",
|
||||
br#"{"template": "minecraft:stone", "glow": true}"#,
|
||||
)],
|
||||
);
|
||||
let e = refused(
|
||||
"clash",
|
||||
&[
|
||||
("data/ruby/horizon/block/a.json", BLOCK),
|
||||
("data/ruby/horizon/item/a.json", ITEM),
|
||||
],
|
||||
);
|
||||
assert!(e.contains("also a block's item"), "{e}");
|
||||
refused("other-kind", &[("data/ruby/horizon/entity/a.json", b"{}")]);
|
||||
refused(
|
||||
"stack",
|
||||
&[(
|
||||
"data/ruby/horizon/item/a.json",
|
||||
br#"{"template": "minecraft:stick", "max_stack_size": 100}"#,
|
||||
)],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_needs_the_registries_capability() {
|
||||
let code_only = MANIFEST_TEXT
|
||||
.replace("api = \"0.2\"", "api = \"0.1\"")
|
||||
.replace("capabilities = [\"registries\"]", "capabilities = []");
|
||||
// No code and no registries: nothing to load.
|
||||
let e = hmod("empty", &code_only, &[]).unwrap_err();
|
||||
assert!(e.contains("mod.wasm: missing"), "{e}");
|
||||
// Registries on API 0.1.
|
||||
let old = MANIFEST_TEXT.replace("api = \"0.2\"", "api = \"0.1\"");
|
||||
assert!(Manifest::parse(&old).unwrap_err().contains("needs api"));
|
||||
// Content without the capability, in a mod with code.
|
||||
let dir = scratch("no-cap");
|
||||
let path = dir.join("m.hmod");
|
||||
let files: &[(&str, &[u8])] = &[("assets/ruby/lang/en_us.json", b"{}")];
|
||||
std::fs::write(
|
||||
&path,
|
||||
Package::write_files(&code_only, Some(b"\0asm"), files).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let package = Package::read(&path).unwrap();
|
||||
let e = Content::read(&path, &package.manifest).err().unwrap();
|
||||
assert!(e.contains("not capability registries"), "{e}");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_are_plain() {
|
||||
assert!(check_path("assets/ruby/textures/block/ruby_block.png").is_ok());
|
||||
assert!(check_path("data/ruby/loot_table/blocks/a.json").is_ok());
|
||||
for bad in [
|
||||
"assets/ruby",
|
||||
"assets/../x/y",
|
||||
"assets/ruby//a",
|
||||
"assets/Ruby/a",
|
||||
"assets/ruby/a b",
|
||||
"/assets/ruby/a",
|
||||
"other/ruby/a",
|
||||
"assets\\ruby\\a",
|
||||
] {
|
||||
assert!(check_path(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,12 @@
|
||||
//!
|
||||
//! Nothing here runs unless a mod is installed and turned on: an empty
|
||||
//! [`Mods`] makes no engine and every hook returns at once.
|
||||
pub mod content;
|
||||
pub mod manifest;
|
||||
#[cfg(feature = "runtime")]
|
||||
mod runtime;
|
||||
|
||||
pub use content::Content;
|
||||
pub use manifest::{Capability, Manifest, Package, Side};
|
||||
#[cfg(feature = "runtime")]
|
||||
pub use runtime::*;
|
||||
|
||||
@@ -9,6 +9,10 @@ pub const WASM: &str = "mod.wasm";
|
||||
/// The API (WIT package `horizon:mods`) versions this build runs: a mod
|
||||
/// built for any 0.1.x SDK.
|
||||
pub const API: &str = "0.1";
|
||||
/// The manifest `api` lines this build loads. 0.2 is 0.1 plus content:
|
||||
/// `assets/` and `data/` in the `.hmod`, with blocks and items declared in
|
||||
/// `data/<id>/horizon/` (docs/modpacks.md). Code still links API 0.1.
|
||||
pub const APIS: [&str; 2] = [API, "0.2"];
|
||||
/// The biggest `mod.wasm` a mod may ship.
|
||||
const MAX_WASM: u64 = 32 << 20;
|
||||
|
||||
@@ -23,7 +27,7 @@ pub struct Manifest {
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub authors: Vec<String>,
|
||||
/// The API version the mod was built for: `0.1`.
|
||||
/// The API line the mod was built for: `0.1`, or `0.2` for content.
|
||||
pub api: String,
|
||||
#[serde(default)]
|
||||
pub side: Side,
|
||||
@@ -51,15 +55,24 @@ pub enum Capability {
|
||||
GameRead,
|
||||
Chat,
|
||||
Hud,
|
||||
/// New blocks and items from the mod's `data/` (API 0.2): no WIT
|
||||
/// interface, the game reads them before the world loads.
|
||||
Registries,
|
||||
}
|
||||
impl Capability {
|
||||
pub const ALL: [Capability; 3] = [Capability::GameRead, Capability::Chat, Capability::Hud];
|
||||
pub const ALL: [Capability; 4] = [
|
||||
Capability::GameRead,
|
||||
Capability::Chat,
|
||||
Capability::Hud,
|
||||
Capability::Registries,
|
||||
];
|
||||
/// The WIT interface it grants, in `horizon:mods`.
|
||||
pub fn interface(self) -> &'static str {
|
||||
match self {
|
||||
Capability::GameRead => "game",
|
||||
Capability::Chat => "chat",
|
||||
Capability::Hud => "hud",
|
||||
Capability::Registries => "registries",
|
||||
}
|
||||
}
|
||||
/// What the player reads before turning the mod on: "May <this>".
|
||||
@@ -68,6 +81,7 @@ impl Capability {
|
||||
Capability::GameRead => "see your position, health and the time",
|
||||
Capability::Chat => "show you chat messages",
|
||||
Capability::Hud => "draw text on your screen",
|
||||
Capability::Registries => "add blocks and items to your worlds",
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
@@ -84,6 +98,7 @@ impl Capability {
|
||||
}
|
||||
Capability::ALL
|
||||
.into_iter()
|
||||
.filter(|c| *c != Capability::Registries)
|
||||
.find(|c| c.interface() == interface)
|
||||
.map(Some)
|
||||
.ok_or_else(unknown)
|
||||
@@ -95,6 +110,7 @@ impl fmt::Display for Capability {
|
||||
Capability::GameRead => "game-read",
|
||||
Capability::Chat => "chat",
|
||||
Capability::Hud => "hud",
|
||||
Capability::Registries => "registries",
|
||||
};
|
||||
f.write_str(name)
|
||||
}
|
||||
@@ -113,8 +129,17 @@ impl Manifest {
|
||||
m.id
|
||||
));
|
||||
}
|
||||
if m.api != API {
|
||||
return Err(format!("built for API {}; this Horizon runs {API}", m.api));
|
||||
if !APIS.contains(&m.api.as_str()) {
|
||||
return Err(format!(
|
||||
"built for API {}; this Horizon runs {}",
|
||||
m.api,
|
||||
APIS.join(" and ")
|
||||
));
|
||||
}
|
||||
if m.capabilities.contains(&Capability::Registries) && m.api == API {
|
||||
return Err(format!(
|
||||
"{MANIFEST}: capability registries needs api = \"0.2\""
|
||||
));
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
@@ -137,54 +162,79 @@ impl Manifest {
|
||||
/// A mod as found on disk: its manifest and component bytes.
|
||||
pub struct Package {
|
||||
pub manifest: Manifest,
|
||||
pub wasm: Vec<u8>,
|
||||
/// None for a content-only mod (capability `registries`, no code).
|
||||
pub wasm: Option<Vec<u8>>,
|
||||
}
|
||||
impl Package {
|
||||
/// A `.hmod` (a zip holding `horizon-mod.toml` and `mod.wasm`) or a
|
||||
/// folder holding the same two files.
|
||||
/// A `.hmod` (a zip holding `horizon-mod.toml`, `mod.wasm` and, for
|
||||
/// content, `assets/` and `data/`) or a folder holding the same.
|
||||
pub fn read(path: &Path) -> Result<Self, String> {
|
||||
let (toml, wasm) = if path.is_dir() {
|
||||
let toml = std::fs::read_to_string(path.join(MANIFEST));
|
||||
let wasm = std::fs::read(path.join(WASM));
|
||||
(
|
||||
toml.map_err(|e| format!("{MANIFEST}: {e}"))?,
|
||||
wasm.map_err(|e| format!("{WASM}: {e}"))?,
|
||||
)
|
||||
let wasm = path.join(WASM);
|
||||
let wasm = match wasm.exists() {
|
||||
true => Some(std::fs::read(wasm).map_err(|e| format!("{WASM}: {e}"))?),
|
||||
false => None,
|
||||
};
|
||||
(toml.map_err(|e| format!("{MANIFEST}: {e}"))?, wasm)
|
||||
} else {
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
let mut entry = |name: &str| -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
|
||||
let mut entry = |name: &str| -> Result<Option<Vec<u8>>, String> {
|
||||
let f = match zip.by_name(name) {
|
||||
Ok(f) => f,
|
||||
Err(zip::result::ZipError::FileNotFound) => return Ok(None),
|
||||
Err(e) => return Err(format!("{name}: {e}")),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
f.take(MAX_WASM + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(out)
|
||||
Ok(Some(out))
|
||||
};
|
||||
let toml = String::from_utf8(entry(MANIFEST)?)
|
||||
.map_err(|_| format!("{MANIFEST}: not UTF-8"))?;
|
||||
let toml = entry(MANIFEST)?.ok_or_else(|| format!("{MANIFEST}: missing"))?;
|
||||
let toml = String::from_utf8(toml).map_err(|_| format!("{MANIFEST}: not UTF-8"))?;
|
||||
(toml, entry(WASM)?)
|
||||
};
|
||||
if wasm.len() as u64 > MAX_WASM {
|
||||
if wasm.as_ref().is_some_and(|w| w.len() as u64 > MAX_WASM) {
|
||||
return Err(format!("{WASM} is over {} MiB", MAX_WASM >> 20));
|
||||
}
|
||||
Ok(Package {
|
||||
manifest: Manifest::parse(&toml)?,
|
||||
wasm,
|
||||
})
|
||||
let manifest = Manifest::parse(&toml)?;
|
||||
if wasm.is_none() && !manifest.capabilities.contains(&Capability::Registries) {
|
||||
return Err(format!(
|
||||
"{WASM}: missing (only a content mod, with capability registries, may have no code)"
|
||||
));
|
||||
}
|
||||
Ok(Package { manifest, wasm })
|
||||
}
|
||||
/// The `.hmod` bytes for `manifest_text` and a component.
|
||||
pub fn write(manifest_text: &str, wasm: &[u8]) -> Result<Vec<u8>, String> {
|
||||
Self::write_files(manifest_text, Some(wasm), &[])
|
||||
}
|
||||
/// The `.hmod` bytes for `manifest_text`, a component if the mod has
|
||||
/// code, and content `files` (`assets/...`, `data/...`) by path.
|
||||
pub fn write_files(
|
||||
manifest_text: &str,
|
||||
wasm: Option<&[u8]>,
|
||||
files: &[(&str, &[u8])],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
use std::io::Write;
|
||||
Manifest::parse(manifest_text)?;
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
let options = zip::write::SimpleFileOptions::default();
|
||||
let err = |e: zip::result::ZipError| e.to_string();
|
||||
zip.start_file(MANIFEST, options).map_err(err)?;
|
||||
zip.write_all(manifest_text.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
zip.start_file(WASM, options).map_err(err)?;
|
||||
zip.write_all(wasm).map_err(|e| e.to_string())?;
|
||||
let mut put = |name: &str, bytes: &[u8]| -> Result<(), String> {
|
||||
zip.start_file(name, options).map_err(err)?;
|
||||
zip.write_all(bytes).map_err(|e| e.to_string())
|
||||
};
|
||||
put(MANIFEST, manifest_text.as_bytes())?;
|
||||
if let Some(wasm) = wasm {
|
||||
put(WASM, wasm)?;
|
||||
}
|
||||
for (name, bytes) in files {
|
||||
crate::content::check_path(name)?;
|
||||
put(name, bytes)?;
|
||||
}
|
||||
Ok(zip.finish().map_err(err)?.into_inner())
|
||||
}
|
||||
}
|
||||
@@ -256,8 +306,8 @@ capabilities = ["game-read", "hud"]
|
||||
fn refuses_bad_ids_and_apis() {
|
||||
let bad_id = EXAMPLE.replace("coords_hud", "Coords HUD");
|
||||
assert!(Manifest::parse(&bad_id).unwrap_err().contains("is not"));
|
||||
let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.2\"");
|
||||
assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.2"));
|
||||
let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.3\"");
|
||||
assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.3"));
|
||||
let unknown = format!("{EXAMPLE}network = true\n");
|
||||
assert!(Manifest::parse(&unknown).is_err());
|
||||
}
|
||||
@@ -270,7 +320,7 @@ capabilities = ["game-read", "hud"]
|
||||
std::fs::write(&path, Package::write(EXAMPLE, b"\0asm").unwrap()).unwrap();
|
||||
let p = Package::read(&path).unwrap();
|
||||
assert_eq!(p.manifest.id, "coords_hud");
|
||||
assert_eq!(p.wasm, b"\0asm");
|
||||
assert_eq!(p.wasm.as_deref(), Some(&b"\0asm"[..]));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,9 +153,12 @@ impl Mods {
|
||||
let on = enabled(&package.manifest.id);
|
||||
entry.manifest = Some(package.manifest.clone());
|
||||
if on {
|
||||
entry.status = match mods.start(&package, &reserved) {
|
||||
// Content is read before the world loads; a mod whose
|
||||
// content is refused stays off, with the reason.
|
||||
let content = crate::Content::read(path, &package.manifest);
|
||||
entry.status = match content.and_then(|_| mods.start(&package, &reserved)) {
|
||||
Ok(run) => {
|
||||
entry.run = Some(run);
|
||||
entry.run = run;
|
||||
Status::Running
|
||||
}
|
||||
Err(e) => Status::Failed(e),
|
||||
@@ -184,12 +187,17 @@ impl Mods {
|
||||
Ok(self.engine.as_ref().expect("made above"))
|
||||
}
|
||||
|
||||
/// Starts a mod's code; `Ok(None)` for a content-only mod, which has
|
||||
/// nothing to run (the game reads its content before the world loads).
|
||||
fn start(
|
||||
&mut self,
|
||||
package: &Package,
|
||||
reserved: &dyn Fn(&str) -> bool,
|
||||
) -> Result<Running, String> {
|
||||
) -> Result<Option<Running>, String> {
|
||||
let m = &package.manifest;
|
||||
let Some(wasm) = &package.wasm else {
|
||||
return Ok(None);
|
||||
};
|
||||
if m.side == Side::Server {
|
||||
return Err("server mods do not run yet".into());
|
||||
}
|
||||
@@ -202,7 +210,7 @@ impl Mods {
|
||||
let snapshot = self.snapshot.clone();
|
||||
let (engine, linker) = self.engine()?;
|
||||
let component =
|
||||
Component::new(engine, &package.wasm).map_err(|e| format!("not a component: {e}"))?;
|
||||
Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?;
|
||||
let ty = component.component_type();
|
||||
let imports: Vec<String> = ty
|
||||
.imports(engine)
|
||||
@@ -237,11 +245,11 @@ impl Mods {
|
||||
free
|
||||
});
|
||||
self.out.append(&mut store.data_mut().out);
|
||||
Ok(Running {
|
||||
Ok(Some(Running {
|
||||
store,
|
||||
exports,
|
||||
hooks,
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
/// True when at least one mod runs: the game skips its mod work otherwise.
|
||||
@@ -403,7 +411,7 @@ impl Mods {
|
||||
match started {
|
||||
Ok(run) => {
|
||||
log::info!("Horizon: mod {id} reloaded");
|
||||
entry.run = Some(run);
|
||||
entry.run = run;
|
||||
entry.status = Status::Running;
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -131,7 +131,8 @@ fn undeclared_capabilities_are_refused() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let wasm = Package::read(&mods_dir().join("horizon_mods_test_guest.hmod"))
|
||||
.unwrap()
|
||||
.wasm;
|
||||
.wasm
|
||||
.expect("the guest has code");
|
||||
let manifest = GUEST_MANIFEST.replace("[\"chat\"]", "[]");
|
||||
std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap();
|
||||
std::fs::write(dir.join("mod.wasm"), wasm).unwrap();
|
||||
@@ -241,3 +242,34 @@ fn hook_overhead() {
|
||||
started.elapsed().as_secs_f64() * 1000.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_only_mods_load_without_an_engine() {
|
||||
let manifest = r#"
|
||||
id = "ruby"
|
||||
name = "Ruby"
|
||||
version = "0.1.0"
|
||||
api = "0.2"
|
||||
side = "both"
|
||||
capabilities = ["registries"]
|
||||
"#;
|
||||
let block: &[u8] = br#"{"template": "minecraft:iron_block"}"#;
|
||||
let dir = mods_dir().join("content");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = dir.join("ruby.hmod");
|
||||
let files: &[(&str, &[u8])] = &[("data/ruby/horizon/block/ruby_block.json", block)];
|
||||
std::fs::write(&ok, Package::write_files(manifest, None, files).unwrap()).unwrap();
|
||||
let bad = dir.join("bad.hmod");
|
||||
let files: &[(&str, &[u8])] = &[("data/minecraft/recipe/stone.json", b"{}")];
|
||||
let bad_manifest = manifest.replace("\"ruby\"", "\"bad\"");
|
||||
std::fs::write(
|
||||
&bad,
|
||||
Package::write_files(&bad_manifest, None, files).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mods = Mods::load(&[ok, bad], |_| true, |_| false);
|
||||
assert_eq!(mods.entries()[0].status, Status::Running);
|
||||
assert!(matches!(&mods.entries()[1].status, Status::Failed(e) if e.contains("own namespace")));
|
||||
// Content has no hooks: the game's per-tick mod work stays skipped.
|
||||
assert!(!mods.is_running());
|
||||
}
|
||||
|
||||
@@ -262,6 +262,28 @@ capabilities = ["game-read", "hud", "chat"]
|
||||
Unknown keys are refused, so a typo is an error, not a silently ignored
|
||||
permission.
|
||||
|
||||
### Content mods (API 0.2)
|
||||
|
||||
A mod with `api = "0.2"` and capability `registries` may carry `assets/` and
|
||||
`data/` in the `.hmod`, and needs no `mod.wasm` if it has no code. It adds
|
||||
blocks and items by declaring them in `data/<id>/horizon/block/*.json` and
|
||||
`data/<id>/horizon/item/*.json`, each copying a vanilla template
|
||||
([modpacks.md](modpacks.md#registries-02-data-driven-blocks-and-items)):
|
||||
|
||||
```json
|
||||
{ "template": "minecraft:iron_block",
|
||||
"properties": { "hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block" },
|
||||
"item": true }
|
||||
```
|
||||
|
||||
The fence: files go in the mod's own namespace (`assets/<id>/`,
|
||||
`data/<id>/`), plus additions to vanilla tags (`data/minecraft/tags/`).
|
||||
Templates and `sounds` name vanilla blocks; unknown keys are refused. Paths
|
||||
use vanilla's resource characters, at most 65,536 files, 16 MiB each and
|
||||
512 MiB in all. A mod whose content is refused stays off, with the reason on
|
||||
its row. The game reading this content into its block and item tables comes
|
||||
next (docs/modpacks.md).
|
||||
|
||||
## Versions and compatibility
|
||||
|
||||
- The API is the WIT package `horizon:mods@0.1.0`. New functions and
|
||||
|
||||
Reference in New Issue
Block a user