Files
horizon-airdef/crates/horizon-port-pack/src/oracle.rs
T
Ludovic Marie 886def4360 horizon-port-pack carry: templates and numbers from the NeoForge oracle, 1.21.1 loot upgraded
Carrying over seven real ATM10 mods (Cloud Glass, Factory Blocks,
Glassential, Macaw's Doors, Fences, Paths and Trapdoors) showed what the
guesses missed:

- Loot tables: 1.21.1's `conditions` lists, `functions` and
  `condition`/`function` kinds are now 26.3's single `condition`,
  `modifier` and `type`; silk-touch and shears tool matches become
  `minecraft:tool/can_silk_touch` and `can_shear`. Before, every drop
  condition was ignored (glass dropped itself by hand, upper door halves
  dropped doors, double slabs dropped one).
- With the oracle's facts (<work>/oracle/facts.json, from
  tools/neoforge_oracle.py in the next PR), every registered block gets
  the vanilla template of the same vanilla class and states that matches
  its shapes, sounds, BlockSetType and WoodType best, and the mod's own
  hardness, blast resistance, light, tool need, friction, map colour and
  sounds. Items get stack size and rarity. The carry report lists what a
  template does not reproduce and why a block was left out.
- Convention tags a recipe uses (c:dyes/red) are written from the
  oracle's tags, vanilla and own members only; the jar's own c tags stay
  inside the mod.
- Without the oracle, blockstates that omit properties their models
  ignore (powered, waterlogged) still find their template, and names pick
  between fences and panes, doors and trapdoors.
- `version = "${file.jarVersion}"` is read from MANIFEST.MF.
- `--resources <prepared>` limits templates to blocks Horizon has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:25:54 +02:00

385 lines
14 KiB
Rust

//! The NeoForge oracle's facts (`tools/neoforge_oracle.py export`, in
//! `<work>/oracle/facts.json`): every block, item, recipe and tag the pack's
//! mods register, read from the running game, and the vanilla blocks beside
//! them. Carry-over uses them in place of guesses: a block's template is the
//! vanilla block of the same class and states whose shapes and sounds match
//! best, and the declared properties are the mod's own numbers.
use serde::Deserialize;
use serde_json::{Map, Value, json};
use std::{
collections::{BTreeMap, BTreeSet},
path::Path,
};
#[derive(Debug, Deserialize)]
pub struct Facts {
pub blocks: BTreeMap<String, Block>,
pub items: BTreeMap<String, Item>,
#[serde(default)]
pub tags: Tags,
}
#[derive(Debug, Default, Deserialize)]
pub struct Tags {
#[serde(default)]
pub block: BTreeMap<String, Vec<String>>,
#[serde(default)]
pub item: BTreeMap<String, Vec<String>>,
}
#[derive(Debug, Deserialize)]
pub struct Block {
/// The class and its superclasses, most derived first.
pub class: Vec<String>,
pub properties: BTreeMap<String, Vec<String>>,
pub default: String,
pub item: String,
pub explosion_resistance: f32,
pub friction: f32,
pub speed_factor: f32,
pub jump_factor: f32,
#[serde(default)]
pub block_set_type: Option<SetType>,
#[serde(default)]
pub wood_type: Option<String>,
pub states: BTreeMap<String, State>,
}
#[derive(Debug, Deserialize)]
pub struct SetType {
pub name: String,
pub can_open_by_hand: bool,
}
#[derive(Debug, Deserialize)]
pub struct State {
pub hardness: f32,
pub emission: u8,
pub requires_tool: bool,
pub map_color_id: u8,
pub sound: Value,
pub outline: Value,
pub collision: Value,
}
#[derive(Debug, Deserialize)]
pub struct Item {
pub class: String,
pub max_stack_size: u8,
pub rarity: String,
#[serde(default)]
pub block: Option<String>,
#[serde(default)]
pub food: Option<Value>,
}
const VANILLA_PACKAGE: &str = "net.minecraft.";
/// A state key with its properties sorted, so keys compare across blocks.
pub fn state_key(key: &str) -> String {
let mut parts: Vec<&str> = key.split(',').filter(|p| !p.is_empty()).collect();
parts.sort_unstable();
parts.join(",")
}
impl Block {
/// The first vanilla class in the chain.
pub fn vanilla_class(&self) -> &str {
self.class
.iter()
.find(|c| c.starts_with(VANILLA_PACKAGE))
.map_or("", String::as_str)
}
/// Its own class is a mod class: behaviour code the template may not have.
pub fn custom_class(&self) -> bool {
self.class
.first()
.is_some_and(|c| !c.starts_with(VANILLA_PACKAGE))
}
fn default_state(&self) -> Option<&State> {
self.states
.get(&self.default)
.or_else(|| self.states.values().next())
}
fn same_states(&self, other: &Block) -> bool {
self.properties.len() == other.properties.len()
&& self.properties.iter().all(|(k, v)| {
other.properties.get(k).is_some_and(|w| {
v.iter().collect::<BTreeSet<_>>() == w.iter().collect::<BTreeSet<_>>()
})
})
}
fn by_key(&self) -> BTreeMap<String, &State> {
self.states.iter().map(|(k, s)| (state_key(k), s)).collect()
}
}
/// The template carry-over gives a mod block.
#[derive(Debug, Clone, PartialEq)]
pub struct Choice {
pub template: String,
/// `data/<mod>/horizon/block/<name>.json`'s `properties`.
pub properties: Map<String, Value>,
/// What the template does not reproduce, for the report.
pub differences: Vec<String>,
}
impl Facts {
pub fn read(path: &Path) -> Result<Facts, String> {
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))
}
/// The vanilla block that best stands in for `id`: the same vanilla
/// class and states, then the most states with the same outline and
/// collision, then the same sounds, set type, wood type and hardness.
/// `None` when no vanilla block has its class and states.
pub fn template(&self, id: &str, allowed: &dyn Fn(&str) -> bool) -> Option<Choice> {
let block = self.blocks.get(id)?;
let class = block.vanilla_class();
let own = block.by_key();
let ours = block.default_state()?;
let mut best: Option<(i64, &str, &Block)> = None;
for (name, v) in &self.blocks {
if !name.starts_with("minecraft:")
|| v.vanilla_class() != class
|| v.custom_class()
|| !block.same_states(v)
|| !allowed(name)
{
continue;
}
let theirs = v.by_key();
let shapes = own
.iter()
.filter(|(k, s)| {
theirs
.get(*k)
.is_some_and(|t| t.outline == s.outline && t.collision == s.collision)
})
.count() as i64;
let Some(td) = v.default_state() else {
continue;
};
let same_set = match (&block.block_set_type, &v.block_set_type) {
(Some(a), Some(b)) => {
(a.name == b.name) as i64 * 2
+ (a.can_open_by_hand == b.can_open_by_hand) as i64 * 8
}
_ => 0,
};
let score = shapes * 1000
+ (td.sound == ours.sound) as i64 * 100
+ same_set * 10
+ (block.wood_type.is_some() && block.wood_type == v.wood_type) as i64 * 20
+ (td.hardness == ours.hardness) as i64 * 5
+ (td.map_color_id == ours.map_color_id) as i64;
if best.is_none_or(|(s, n, _)| score > s || (score == s && name.as_str() < n)) {
best = Some((score, name, v));
}
}
let (_, template, t) = best?;
Some(self.choice(block, template, t, allowed))
}
fn choice(
&self,
block: &Block,
template: &str,
t: &Block,
allowed: &dyn Fn(&str) -> bool,
) -> Choice {
let (ours, theirs) = (block.default_state(), t.default_state());
let mut properties = Map::new();
let mut differences = Vec::new();
if let Some(s) = ours {
properties.insert("hardness".into(), json!(s.hardness));
properties.insert(
"explosion_resistance".into(),
json!(block.explosion_resistance),
);
properties.insert("light".into(), json!(s.emission));
properties.insert("requires_tool".into(), json!(s.requires_tool));
properties.insert("friction".into(), json!(block.friction));
properties.insert("map_color".into(), json!(s.map_color_id));
if theirs.is_none_or(|t| t.sound != s.sound) {
match self.sound_block(&s.sound, allowed) {
Some(b) => {
properties.insert("sounds".into(), json!(b));
}
None => differences.push("sounds: no vanilla block has them".into()),
}
}
}
if (block.speed_factor, block.jump_factor) != (t.speed_factor, t.jump_factor) {
differences.push(format!(
"speed and jump factors {} {} (template {} {})",
block.speed_factor, block.jump_factor, t.speed_factor, t.jump_factor
));
}
let theirs = t.by_key();
let mut shapes = 0;
let mut varying = BTreeSet::new();
let first = ours.map(|s| (s.hardness, s.emission, s.requires_tool, s.map_color_id));
for (k, s) in block.by_key() {
let Some(v) = theirs.get(&k) else {
continue;
};
if v.outline != s.outline || v.collision != s.collision {
shapes += 1;
}
if Some((s.hardness, s.emission, s.requires_tool, s.map_color_id)) != first {
varying.insert("per-state hardness, light or map colour");
}
}
if shapes > 0 {
differences.push(format!(
"shapes differ from {template} in {shapes} of {} states",
block.states.len()
));
}
differences.extend(varying.into_iter().map(str::to_owned));
if block.custom_class() {
differences.push(format!(
"class {} (behaviour beyond {})",
block.class[0],
block.vanilla_class()
));
}
Choice {
template: template.to_owned(),
properties,
differences,
}
}
/// A vanilla block whose default state has these sounds.
fn sound_block(&self, sound: &Value, allowed: &dyn Fn(&str) -> bool) -> Option<&str> {
self.blocks
.iter()
.filter(|(n, _)| n.starts_with("minecraft:") && allowed(n))
.find(|(_, b)| b.default_state().is_some_and(|s| &s.sound == sound))
.map(|(n, _)| n.as_str())
}
/// An item declaration for a mod item that is not a declared block's:
/// a vanilla template item with its stack size and rarity, and what it
/// does not reproduce.
pub fn item(&self, id: &str) -> Result<(Value, Vec<String>), String> {
let item = self.items.get(id).ok_or("not in the oracle")?;
if item.block.is_some() {
return Err("a block item without a block".into());
}
let mut differences = Vec::new();
if !item.class.starts_with(VANILLA_PACKAGE) {
differences.push(format!("class {} (behaviour beyond Item)", item.class));
}
if item.food.is_some() {
return Err("food (no food template yet)".into());
}
let mut decl = json!({"template": "minecraft:stick"});
if item.max_stack_size != 64 {
decl["max_stack_size"] = json!(item.max_stack_size);
}
if item.rarity != "common" {
decl["rarity"] = json!(item.rarity);
}
Ok((decl, differences))
}
/// A tag's members the content mod may name: vanilla's and its own.
pub fn tag_members(&self, kind: &str, tag: &str, own: &str) -> Option<Vec<String>> {
let map = if kind == "block" {
&self.tags.block
} else {
&self.tags.item
};
let members = map.get(tag)?;
Some(
members
.iter()
.filter(|m| {
m.split_once(':')
.is_some_and(|(ns, _)| ns == "minecraft" || ns == own)
})
.cloned()
.collect(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn state(hardness: f32, sound: &str, outline: Value) -> Value {
json!({"hardness": hardness, "emission": 0, "requires_tool": false, "map_color_id": 13,
"sound": {"break": sound}, "outline": outline, "collision": outline})
}
fn block(class: &[&str], props: Value, states: Value) -> Value {
let default = states
.as_object()
.unwrap()
.keys()
.next()
.unwrap()
.to_owned();
json!({"class": class, "properties": props, "default": default, "item": "x",
"explosion_resistance": 3.0, "friction": 0.6, "speed_factor": 1.0,
"jump_factor": 1.0, "states": states})
}
#[test]
fn templates_follow_class_shapes_and_sounds() {
let cube = json!([[0, 0, 0, 1, 1, 1]]);
let low = json!([[0, 0, 0, 1, 0.9375, 1]]);
let block_class = ["net.minecraft.world.level.block.Block"];
let path = ["net.minecraft.world.level.block.DirtPathBlock"];
let facts: Facts = serde_json::from_value(json!({
"blocks": {
"minecraft:stone": block(&block_class, json!({}), json!({"": state(1.5, "stone", cube.clone())})),
"minecraft:oak_planks": block(&block_class, json!({}), json!({"": state(2.0, "wood", cube.clone())})),
"minecraft:dirt_path": block(&path, json!({}), json!({"": state(0.65, "grass", low.clone())})),
"m:wood_tile": block(&["m.Tile", block_class[0]], json!({}), json!({"": state(2.5, "wood", cube.clone())})),
"m:path": block(&["m.Path", block_class[0]], json!({}), json!({"": state(1.0, "stone", low.clone())})),
"m:gadget": block(&["m.Gadget", block_class[0]], json!({"mode": ["a", "b"]}),
json!({"mode=a": state(1.0, "stone", cube.clone()), "mode=b": state(1.0, "stone", cube)})),
},
"items": {}
}))
.unwrap();
let any = |_: &str| true;
let tile = facts.template("m:wood_tile", &any).unwrap();
assert_eq!(tile.template, "minecraft:oak_planks");
assert_eq!(tile.properties["hardness"], json!(2.5));
assert!(!tile.properties.contains_key("sounds"));
assert_eq!(
tile.differences,
["class m.Tile (behaviour beyond net.minecraft.world.level.block.Block)"]
);
// A plain Block is never templated on a DirtPathBlock: shapes differ, and say so.
let path = facts.template("m:path", &any).unwrap();
assert_eq!(path.template, "minecraft:stone");
assert!(
path.differences[0].starts_with("shapes differ"),
"{:?}",
path.differences
);
assert_eq!(facts.template("m:gadget", &any), None);
let tile = facts
.template("m:wood_tile", &|n: &str| n != "minecraft:oak_planks")
.unwrap();
assert_eq!(tile.template, "minecraft:stone");
assert_eq!(tile.differences[0], "sounds: no vanilla block has them");
}
#[test]
fn state_keys_sort() {
assert_eq!(
state_key("half=lower,facing=north"),
"facing=north,half=lower"
);
assert_eq!(state_key(""), "");
}
}