diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 39fde56b5..d3e00daca 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -28,7 +28,7 @@ use std::{fs, io, path::Path, sync::Arc}; pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result> { let data = nbt::read_named( &fs::read(root.join("cached-collision.nbt"))?, - Limits::default(), + Limits::tables(), )? .0 .tag; diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 0aca99cef..54a505ab9 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -274,16 +274,20 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result Result>> { - let dir = root.join(format!("data/minecraft/tags/{kind}")); let mut raw: HashMap> = HashMap::new(); - fn walk(dir: &Path, base: &Path, raw: &mut HashMap>) -> Result<()> { + fn walk( + dir: &Path, + base: &Path, + namespace: &str, + raw: &mut HashMap>, + ) -> Result<()> { for entry in fs::read_dir(dir)?.flatten() { let p = entry.path(); if p.is_dir() { - walk(&p, base, raw)?; + walk(&p, base, namespace, raw)?; } else if p.extension().is_some_and(|e| e == "json") { let name = format!( - "minecraft:{}", + "{namespace}:{}", p.strip_prefix(base)? .with_extension("") .to_string_lossy() @@ -301,8 +305,12 @@ pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result>, out: &mut Vec, depth: u32) { if depth > 32 { diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 936bc9655..fd271f40f 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -71,7 +71,7 @@ impl LightTables { }; let data = nbt::read_named( &std::fs::read(root.join("occlusion.nbt"))?, - Limits::default(), + Limits::tables(), )? .0 .tag; diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index 3a8c2920e..4556a4d6c 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -638,6 +638,19 @@ pub fn namespaces(root: &Path) -> Vec { .unwrap_or_default() } +/// The namespaces whose tags loaders read in `root`: `minecraft`, and in a +/// root built by [`build`] the convention tags (`c`, shared between mods as +/// on NeoForge and Fabric) and the content mods' own. +pub fn tag_namespaces(root: &Path) -> Vec { + let mods = namespaces(root); + let mut out = vec!["minecraft".to_owned()]; + if !mods.is_empty() { + out.push("c".to_owned()); + out.extend(mods); + } + out +} + /// Bundles of block tag files (tag id → the tag file's text). const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; @@ -735,8 +748,67 @@ fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result { Ok(serde_json::to_string_pretty(&doc)?) } +/// The block and item ids and tags a content root has, for tag entries. +struct Known { + blocks: std::collections::BTreeSet, + items: std::collections::BTreeSet, + /// `data//tags//.json` files the mods add. + tag_files: std::collections::BTreeSet, +} +impl Known { + fn new(base: &Path, plan: &Plan, tags: &BTreeMap>) -> Result { + let mut blocks: std::collections::BTreeSet = + plan.defaults.keys().cloned().collect(); + blocks.extend(plan.blocks.iter().map(|b| b.decl.id.clone())); + let mut items = std::collections::BTreeSet::new(); + if let J::Obj(o) = read_json(&base.join("items.json"))? { + items.extend(o.into_iter().map(|(k, _)| k)); + } + items.extend(plan.items.iter().map(|i| i.rename.to.clone())); + Ok(Known { + blocks, + items, + tag_files: tags.keys().cloned().collect(), + }) + } + /// Whether tag `file` keeps entry `v`: a known id or an existing tag, + /// for block and item tags (other registries are kept as they are). + fn keeps(&self, file: &str, v: &J) -> bool { + let id = match v { + J::Str(s) => s.as_str(), + J::Obj(_) => match v.get("id") { + Some(J::Str(s)) => s.as_str(), + _ => return true, + }, + _ => return true, + }; + let Some(kind) = file + .strip_prefix("data/") + .and_then(|r| r.split_once("/tags/")) + .and_then(|(_, rest)| Some(rest.split_once('/')?.0)) + else { + return true; + }; + let ids = match kind { + "block" => &self.blocks, + "item" => &self.items, + _ => return true, + }; + match id.strip_prefix('#') { + Some(tag) => { + let (tns, path) = tag.split_once(':').unwrap_or(("minecraft", tag)); + let rel = format!("data/{tns}/tags/{kind}/{path}.json"); + self.tag_files.contains(&rel) || tns == "minecraft" + } + None => ids.contains(id), + } + } +} + /// Builds the content root for `mods` over `base` in `out`. pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { + // The overlay links to the base: a relative base would leave them dangling. + let base = &std::path::absolute(base)?; let plan = Plan::new(base, mods)?; let overlay = Overlay::new(base, out)?; for name in JSON_TABLES { @@ -754,11 +826,11 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { if !path.exists() { continue; } - let (mut named, _) = nbt::read_named(&fs::read(&path)?, Limits::default()) + let (mut named, _) = nbt::read_named(&fs::read(&path)?, Limits::tables()) .map_err(|e| format!("{name}: {e}"))?; plan.nbt(&mut named.tag); let bytes = - nbt::write_named(&named, Limits::default()).map_err(|e| format!("{name}: {e}"))?; + nbt::write_named(&named, Limits::tables()).map_err(|e| format!("{name}: {e}"))?; overlay.write(name, &bytes)?; } // Mod files, and every tag addition gathered per tag file. @@ -788,6 +860,13 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { } } } + // A tag naming an id nobody registers fails as a whole in vanilla, and + // carried-over mods name blocks left out or other mods' ids: such + // entries are dropped instead, so the rest of the tag holds. + let known = Known::new(base, &plan, &tags)?; + for (file, values) in &mut tags { + values.retain(|v| known.keeps(file, v)); + } let mut bundles: Vec<(&str, J)> = Vec::new(); for name in TAG_BUNDLES { if base.join(name).exists() { diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 6dd92ecfd..d7627fa27 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -56,7 +56,7 @@ fn prepared() -> Option { /// A content mod folder: a full block, a door and an item-less glass from /// templates, an item, a vanilla tag addition and a language file. fn ruby_mod(dir: &Path) -> ContentMod { - let files: [(&str, &str); 7] = [ + let files: [(&str, &str); 8] = [ ( "horizon-mod.toml", "id = \"ruby\"\nname = \"Ruby\"\nversion = \"0.1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", @@ -78,9 +78,15 @@ fn ruby_mod(dir: &Path) -> ContentMod { "data/ruby/horizon/item/ruby.json", r#"{"template": "minecraft:diamond", "max_stack_size": 16, "rarity": "rare"}"#, ), + // Carried-over tags name blocks left out and other mods' ids too. ( "data/minecraft/tags/block/mineable/pickaxe.json", - r#"{"values": ["ruby:ruby_block"]}"#, + r##"{"values": ["ruby:ruby_block", "ruby:left_out", "othermod:thing", + {"id": "othermod:optional", "required": false}, "#c:storage_blocks/ruby"]}"##, + ), + ( + "data/c/tags/item/gems/ruby.json", + r#"{"values": ["ruby:ruby", "othermod:ruby"]}"#, ), ( "assets/ruby/lang/en_us.json", @@ -110,7 +116,10 @@ fn content_root_loads_with_every_table() { let scratch = std::env::temp_dir().join(format!("horizon-mod-content-{}", std::process::id())); let _ = fs::remove_dir_all(&scratch); let m = ruby_mod(&scratch.join("ruby")); - let root = resource_root(&base, std::slice::from_ref(&m), &scratch.join("cache")).unwrap(); + // The base as a relative path (cargo runs tests in the crate's folder): + // the overlay's links still resolve. + let relative = Path::new("../../.local/horizon-client/26.3"); + let root = resource_root(relative, std::slice::from_ref(&m), &scratch.join("cache")).unwrap(); assert_ne!(root, base); let vanilla = Assets::load(&base).unwrap(); @@ -169,7 +178,12 @@ fn content_root_loads_with_every_table() { let gem = &items.items["ruby:ruby"]; assert_eq!(gem.max_stack, 16); assert!(!items.items.contains_key("ruby:ruby_glass")); - assert!(items.block_tags["minecraft:mineable/pickaxe"].contains("ruby:ruby_block")); + let pickaxe = &items.block_tags["minecraft:mineable/pickaxe"]; + assert!(pickaxe.contains("ruby:ruby_block")); + assert!(!pickaxe.contains("ruby:left_out") && !pickaxe.contains("othermod:thing")); + assert!(pickaxe.contains("minecraft:stone")); + // Convention tags load, with the ids nobody registers dropped. + assert_eq!(items.item_tag_order["c:gems/ruby"], ["ruby:ruby"]); crate::collisions::load(&root, new).unwrap(); crate::models::load_visibility(&root, new).unwrap(); diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index ba5bffefb..110166f29 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -120,7 +120,7 @@ pub fn load_visibility( nbt::{self, Limits}, }; use std::{collections::BTreeMap, fs}; - let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::default())? + let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::tables())? .0 .tag; let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index b098142dc..ae2486351 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -63,7 +63,7 @@ impl MotionResources { )?)?)?); let data = nbt::read_named( &fs::read(root.join("movement-properties.nbt"))?, - Limits::default(), + Limits::tables(), )? .0 .tag; diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 35b02c12e..613086112 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -481,23 +481,30 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient { } impl StationRecipes { pub fn load(root: &Path, items: &Items) -> Self { - let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe")) - .into_iter() - .flatten() - .flatten() - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e == "json")) - .collect(); - files.sort(); + // Vanilla's recipes, then the content mods' (docs/modpacks.md). + let mut files = Vec::new(); + let namespaces = + std::iter::once("minecraft".to_owned()).chain(crate::mod_content::namespaces(root)); + for namespace in namespaces { + let mut more: Vec<_> = fs::read_dir(root.join(format!("data/{namespace}/recipe"))) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + more.sort(); + files.extend(more.into_iter().map(|p| (namespace.clone(), p))); + } let mut smithing = Vec::new(); let mut stonecutting = Vec::new(); - for p in files { + for (namespace, p) in files { let Ok(bytes) = fs::read(&p) else { continue }; let Ok(v) = serde_json::from_slice::(&bytes) else { continue; }; let id = format!( - "minecraft:{}", + "{namespace}:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("") ); match v["type"].as_str().unwrap_or("") { diff --git a/crates/horizon-mods/src/content.rs b/crates/horizon-mods/src/content.rs index 411fa7277..40b641759 100644 --- a/crates/horizon-mods/src/content.rs +++ b/crates/horizon-mods/src/content.rs @@ -4,7 +4,7 @@ //! //! 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 +//! tags and to the convention tags (`c`, which NeoForge and Fabric mods share). Paths are plain, files and totals are capped, and vanilla ids //! cannot be redefined. use crate::manifest::{Capability, MANIFEST, Manifest}; use serde::Deserialize; @@ -242,12 +242,13 @@ impl Content { 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/")); + // Vanilla's own files stay vanilla's; a mod may only add to its + // tags, and to the convention tags mods share. + let shared = matches!(namespace, "minecraft" | "c"); + let allowed = own || (top == "data" && shared && rest.starts_with("tags/")); if !allowed { return Err(format!( - "{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla tags" + "{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla and convention (c) tags" )); } let Some(decl) = (own && top == "data") @@ -417,10 +418,11 @@ capabilities = ["registries"] ("data/ruby/horizon/item/ruby.json", ITEM), ("data/ruby/recipe/ruby_block.json", b"{}"), ("data/minecraft/tags/block/mineable/pickaxe.json", b"{}"), + ("data/c/tags/item/gems/ruby.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.files.len(), 6); assert_eq!( content.blocks, [Block { @@ -471,6 +473,8 @@ capabilities = ["registries"] "vanilla-recipe", &[("data/minecraft/recipe/stone.json", b"{}")], ); + refused("convention-recipe", &[("data/c/recipe/stone.json", b"{}")]); + refused("convention-asset", &[("assets/c/lang/en_us.json", b"{}")]); let e = refused( "modded-template", &[( diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs index 9d5b9355a..7e4d76a41 100644 --- a/crates/horizon-world/src/nbt.rs +++ b/crates/horizon-world/src/nbt.rs @@ -97,6 +97,18 @@ impl Default for Limits { } } } +impl Limits { + /// The prepared per-state block tables (`cached-collision.nbt`, + /// `block-properties.nbt`, ...): trusted files with a row per block + /// state, which content mods' states grow past the default caps. + pub fn tables() -> Self { + Self { + max_bytes: 1 << 28, + max_nodes: 16_000_000, + max_depth: 512, + } + } +} #[derive(Clone, Debug, PartialEq, Eq)] pub struct Error { diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs index 6085183ec..dc7db7d20 100644 --- a/crates/horizon-world/src/worldgen/generator_blocks.rs +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -103,14 +103,12 @@ impl BlockBehavior { return Ok(None); } let read = |name: &str| -> Result { - let limits = Limits { - max_bytes: 1 << 28, - ..Limits::default() - }; - Ok(nbt::read_named(&fs::read(dir.join(name))?, limits) - .map_err(|e| resource(format!("{name}: {e:?}")))? - .0 - .tag) + Ok( + nbt::read_named(&fs::read(dir.join(name))?, Limits::tables()) + .map_err(|e| resource(format!("{name}: {e:?}")))? + .0 + .tag, + ) }; let json = |name: &str| -> Result { Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) diff --git a/docs/mods.md b/docs/mods.md index 6203c4066..d1556abd7 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -277,12 +277,15 @@ blocks and items by declaring them in `data//horizon/block/*.json` and ``` The fence: files go in the mod's own namespace (`assets//`, -`data//`), plus additions to vanilla tags (`data/minecraft/tags/`). +`data//`), plus additions to vanilla tags (`data/minecraft/tags/`) and +to the convention tags NeoForge and Fabric mods share (`data/c/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). +its row. The game reads this content into its block and item tables +(`horizon_client::mod_content`, docs/modpacks.md). A tag entry naming an id +nobody registers (a block a port left out, another mod's item) is dropped, +so the rest of the tag still loads; vanilla would drop the whole tag. ## Versions and compatibility