From 9d624d01751fc5ec2fcca5d4761af0af7ba80bd1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:03:28 +0200 Subject: [PATCH] Add item components (enchantments, name, potion, trim) and the enchantment registry Item stacks carry vanilla's extra components, saved in chunk and player NBT. The enchantment registry loads from the data pack with ordered tags, the EnchantmentHelper cost/selection rules, value effects and level-based values, and the anvil, grindstone, smithing and stonecutter result rules. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/containers.rs | 2 +- crates/horizon-client/src/crafting.rs | 1 + crates/horizon-client/src/enchant.rs | 700 ++++++++++++++++++++++ crates/horizon-client/src/game.rs | 28 +- crates/horizon-client/src/game/control.rs | 1 + crates/horizon-client/src/item_data.rs | 261 ++++++++ crates/horizon-client/src/items.rs | 10 +- crates/horizon-client/src/lib.rs | 3 + crates/horizon-client/src/save.rs | 26 +- crates/horizon-client/src/stations.rs | 572 ++++++++++++++++++ 10 files changed, 1581 insertions(+), 23 deletions(-) create mode 100644 crates/horizon-client/src/enchant.rs create mode 100644 crates/horizon-client/src/item_data.rs create mode 100644 crates/horizon-client/src/stations.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 2eed1860c..e53fb0531 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -208,7 +208,7 @@ impl Furnace { let item = f.item.clone(); f.count -= 1; if f.count == 0 { - self.items[1] = remainder(&item).map(|r| ItemStack { item: Arc::from(r), count: 1, damage: 0 }); + self.items[1] = remainder(&item).map(|r| ItemStack { item: Arc::from(r), count: 1, damage: 0, extra: None }); } } lit = true; diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 6d2c876b3..ba8ddb74e 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -68,6 +68,7 @@ fn result(v: &Value) -> Option { item: Arc::from(v["id"].as_str()?), count: v["count"].as_u64().unwrap_or(1) as u32, damage: 0, + extra: None, }) } impl Recipes { diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs new file mode 100644 index 000000000..0204e951e --- /dev/null +++ b/crates/horizon-client/src/enchant.rs @@ -0,0 +1,700 @@ +//! Data-driven enchantments (`data/minecraft/enchantment/*.json`): the +//! registry, ordered enchantment tags, `EnchantmentHelper` selection and cost +//! rules used by the enchanting table, display names, and evaluation of the +//! value/attribute effect components (`LevelBasedValue`, `EnchantmentValueEffect` +//! and the loot-condition subset that enchantment requirements use). +use crate::items::{ItemStack, Items}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + fs, + path::Path, + sync::Arc, +}; + +/// `Enchantment.Cost`: base + per_level_above_first * (level - 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cost { + pub base: i32, + pub per_level: i32, +} +impl Cost { + fn parse(v: &Value) -> Self { + Self { base: v["base"].as_i64().unwrap_or(1) as i32, per_level: v["per_level_above_first"].as_i64().unwrap_or(0) as i32 } + } + pub fn calculate(self, level: u32) -> i32 { + self.base + self.per_level * (level as i32 - 1) + } +} +#[derive(Clone, Debug)] +pub struct Enchantment { + pub id: Arc, + pub description: String, + pub max_level: u32, + pub weight: u32, + pub anvil_cost: u32, + pub min_cost: Cost, + pub max_cost: Cost, + /// `supported_items` / `primary_items`: item ids or `#tags`. + pub supported: Vec, + pub primary: Option>, + pub exclusive: HashSet>, + pub slots: Vec, + pub effects: Value, +} +/// Item components the enchanting, anvil and smithing rules read. +#[derive(Clone, Debug, Default)] +pub struct ItemProps { + /// `minecraft:enchantable.value`. + pub enchantable: u32, + /// `minecraft:repairable.items` (ids or a `#tag`). + pub repairable: Vec, + pub glint: bool, + pub rarity: String, + /// `minecraft:provides_trim_material`. + pub trim_material: Option, + /// `minecraft:brewing_fuel` present. + pub brewing_fuel: bool, +} +pub struct Enchantments { + pub list: Vec, + index: HashMap, usize>, + /// Enchantment tags in vanilla `HolderSet` order (nested tags expanded in place). + pub tags: HashMap>>, + pub entity_tags: HashMap>, + pub damage_tags: HashMap>, + pub props: HashMap, ItemProps>, + lang: HashMap, +} + +fn string_list(v: &Value) -> Vec { + match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|e| e.as_str().map(str::to_owned)).collect(), + _ => vec![], + } +} +fn read_tag_dir(dir: &Path) -> HashMap> { + fn walk(dir: &Path, base: &Path, out: &mut HashMap>) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, base, out); + } else if p.extension().is_some_and(|x| x == "json") + && let Ok(rel) = p.strip_prefix(base) + && let Ok(bytes) = fs::read(&p) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + let name = format!("minecraft:{}", rel.with_extension("").to_string_lossy().replace('\\', "/")); + let values = v["values"].as_array().into_iter().flatten().filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)).collect(); + out.insert(name, values); + } + } + } + let mut out = HashMap::new(); + walk(dir, dir, &mut out); + out +} +/// Expand a tag keeping first-seen order (`TagLoader` builds a linked set). +fn expand_ordered(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { + if depth > 16 { + return; + } + for v in raw.get(name).into_iter().flatten() { + match v.strip_prefix('#') { + Some(t) => expand_ordered(t, raw, out, depth + 1), + None if !out.contains(v) => out.push(v.clone()), + None => {} + } + } +} +/// Roman numerals as in `enchantment.level.N` (falls back to the number). +pub fn level_name(level: u32) -> String { + const NAMES: [&str; 10] = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]; + NAMES.get(level.wrapping_sub(1) as usize).map_or_else(|| level.to_string(), |s| (*s).to_owned()) +} + +impl Enchantments { + pub fn load(root: &Path) -> Self { + let data = root.join("data/minecraft"); + let raw_tags = read_tag_dir(&data.join("tags/enchantment")); + let tags: HashMap>> = raw_tags + .keys() + .map(|k| { + let mut v = Vec::new(); + expand_ordered(k, &raw_tags, &mut v, 0); + (k.clone(), v.into_iter().map(|s| Arc::from(s.as_str())).collect()) + }) + .collect(); + let unordered = |raw: HashMap>| -> HashMap> { + raw.keys() + .map(|k| { + let mut v = Vec::new(); + expand_ordered(k, &raw, &mut v, 0); + (k.clone(), v.into_iter().collect()) + }) + .collect() + }; + let entity_tags = unordered(read_tag_dir(&data.join("tags/entity_type"))); + let damage_tags = unordered(read_tag_dir(&data.join("tags/damage_type"))); + // The registry lists entries sorted by id, like the data-pack loader. + let mut files: BTreeMap = BTreeMap::new(); + if let Ok(entries) = fs::read_dir(data.join("enchantment")) { + for e in entries.flatten() { + let p = e.path(); + if let (Some(stem), Ok(bytes)) = (p.file_stem().and_then(|s| s.to_str()), fs::read(&p)) + && let Ok(v) = serde_json::from_slice(&bytes) + { + files.insert(format!("minecraft:{stem}"), v); + } + } + } + let lang: HashMap = fs::read(root.join("assets/minecraft/lang/en_us.json")) + .ok() + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default() + .into_iter() + .filter(|(k, _)| k.starts_with("enchantment.") || k.starts_with("effect.") || k.starts_with("item.minecraft.potion") || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") || k.starts_with("merchant.") || k.starts_with("entity.minecraft.villager")) + .collect(); + let mut list = Vec::new(); + for (id, v) in &files { + let exclusive = match &v["exclusive_set"] { + Value::String(s) if s.starts_with('#') => tags.get(&s[1..]).cloned().unwrap_or_default(), + other => string_list(other).into_iter().map(|s| Arc::from(s.as_str())).collect(), + }; + let key = v["description"]["translate"].as_str().unwrap_or(""); + list.push(Enchantment { + id: Arc::from(id.as_str()), + description: lang.get(key).cloned().unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")), + max_level: v["max_level"].as_u64().unwrap_or(1) as u32, + weight: v["weight"].as_u64().unwrap_or(1) as u32, + anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32, + min_cost: Cost::parse(&v["min_cost"]), + max_cost: Cost::parse(&v["max_cost"]), + supported: string_list(&v["supported_items"]), + primary: v.get("primary_items").map(string_list), + exclusive: exclusive.into_iter().collect(), + slots: string_list(&v["slots"]), + effects: v["effects"].clone(), + }); + } + let index = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + let mut props = HashMap::new(); + if let Ok(bytes) = fs::read(root.join("items.json")) + && let Ok(raw) = serde_json::from_slice::>(&bytes) + { + for (id, c) in raw { + props.insert( + Arc::from(id.as_str()), + ItemProps { + enchantable: c["minecraft:enchantable"]["value"].as_u64().unwrap_or(0) as u32, + repairable: string_list(&c["minecraft:repairable"]["items"]), + glint: c["minecraft:enchantment_glint_override"].as_bool().unwrap_or(false), + rarity: c["minecraft:rarity"].as_str().unwrap_or("common").to_owned(), + trim_material: c["minecraft:provides_trim_material"].as_str().map(str::to_owned), + brewing_fuel: c.get("minecraft:brewing_fuel").is_some(), + }, + ); + } + } + Self { list, index, tags, entity_tags, damage_tags, props, lang } + } + pub fn get(&self, id: &str) -> Option<&Enchantment> { + self.index.get(id).map(|&i| &self.list[i]) + } + pub fn tag(&self, name: &str) -> &[Arc] { + self.tags.get(name.trim_start_matches('#')).map_or(&[], Vec::as_slice) + } + pub fn in_tag(&self, name: &str, id: &str) -> bool { + self.tag(name).iter().any(|e| &**e == id) + } + pub fn is_curse(&self, id: &str) -> bool { + self.in_tag("minecraft:curse", id) + } + pub fn translate(&self, key: &str) -> Option<&str> { + self.lang.get(key).map(String::as_str) + } + pub fn props(&self, item: &str) -> Option<&ItemProps> { + self.props.get(item) + } + pub fn enchantable(&self, item: &str) -> u32 { + self.props(item).map_or(0, |p| p.enchantable) + } + /// Whether `item` matches an id / `#tag` list. + pub fn item_in(items: &Items, specs: &[String], item: &str) -> bool { + specs.iter().any(|s| match s.strip_prefix('#') { + Some(tag) => items.item_tags.get(tag).is_some_and(|t| t.contains(item)), + None => s == item, + }) + } + /// `Enchantment.canEnchant` / `isSupportedItem`. + pub fn can_enchant(&self, items: &Items, id: &str, item: &str) -> bool { + self.get(id).is_some_and(|e| Self::item_in(items, &e.supported, item)) + } + /// `Enchantment.isPrimaryItem`. + pub fn is_primary(&self, items: &Items, e: &Enchantment, item: &str) -> bool { + Self::item_in(items, &e.supported, item) && e.primary.as_ref().is_none_or(|p| Self::item_in(items, p, item)) + } + /// `Enchantment.areCompatible`. + pub fn compatible(&self, a: &str, b: &str) -> bool { + if a == b { + return false; + } + let excl = |x: &str, y: &str| self.get(x).is_some_and(|e| e.exclusive.contains(y)); + !excl(a, b) && !excl(b, a) + } + /// `Enchantment.getFullname` as plain text and whether it is a curse (red). + pub fn full_name(&self, id: &str, level: u32) -> (String, bool) { + let Some(e) = self.get(id) else { return (format!("{id} {}", level_name(level)), false) }; + let mut name = e.description.clone(); + if level != 1 || e.max_level != 1 { + name.push(' '); + name.push_str(self.lang.get(&format!("enchantment.level.{level}")).map_or(&level_name(level), |s| s)); + } + (name, self.is_curse(id)) + } + /// Tooltip lines for a level list, in `#tooltip_order` then remaining order. + pub fn tooltip(&self, levels: &[(Arc, u32)]) -> Vec<(String, bool)> { + let order = self.tag("minecraft:tooltip_order"); + let mut out = Vec::new(); + for id in order { + if let Some((_, l)) = levels.iter().find(|(e, _)| e == id) { + out.push(self.full_name(id, *l)); + } + } + for (id, l) in levels { + if !order.contains(id) { + out.push(self.full_name(id, *l)); + } + } + out + } + /// Whether a stack draws the enchantment glint. + pub fn has_glint(&self, stack: &ItemStack) -> bool { + stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint) + } + + // ---- Enchanting table (EnchantmentHelper) ---- + + /// `EnchantmentHelper.getEnchantmentCost`. + pub fn enchantment_cost(&self, random: &mut LegacyRandom, slot: usize, bookcases: i32, item: &str) -> i32 { + if self.enchantable(item) == 0 { + return 0; + } + let bookcases = bookcases.min(15); + let selected = next_int(random, 8) + 1 + (bookcases >> 1) + next_int(random, bookcases + 1); + match slot { + 0 => (selected / 3).max(1), + 1 => selected * 2 / 3 + 1, + _ => selected.max(bookcases * 2), + } + } + /// `EnchantmentHelper.getAvailableEnchantmentResults`. + pub fn available_results(&self, items: &Items, value: i32, item: &str, pool: &[Arc]) -> Vec<(Arc, u32)> { + let book = item == "minecraft:book"; + let mut out = Vec::new(); + for id in pool { + let Some(e) = self.get(id) else { continue }; + if !(book || self.is_primary(items, e, item)) { + continue; + } + for level in (1..=e.max_level).rev() { + if value >= e.min_cost.calculate(level) && value <= e.max_cost.calculate(level) { + out.push((e.id.clone(), level)); + break; + } + } + } + out + } + fn weighted(&self, random: &mut LegacyRandom, list: &[(Arc, u32)]) -> Option<(Arc, u32)> { + let total: i32 = list.iter().map(|(id, _)| self.get(id).map_or(0, |e| e.weight as i32)).sum(); + if total <= 0 { + return None; + } + let mut index = next_int(random, total); + for (id, l) in list { + index -= self.get(id).map_or(0, |e| e.weight as i32); + if index < 0 { + return Some((id.clone(), *l)); + } + } + None + } + /// `EnchantmentHelper.selectEnchantment`. + pub fn select(&self, items: &Items, random: &mut LegacyRandom, item: &str, cost: i32, pool: &[Arc]) -> Vec<(Arc, u32)> { + let mut results = Vec::new(); + let value = self.enchantable(item) as i32; + if value == 0 { + return results; + } + let mut cost = cost + 1 + next_int(random, value / 4 + 1) + next_int(random, value / 4 + 1); + let span = (random.next_float() + random.next_float() - 1.0) * 0.15; + cost = ((cost as f32 + cost as f32 * span).round() as i32).max(1); + let mut available = self.available_results(items, cost, item, pool); + if !available.is_empty() { + if let Some(first) = self.weighted(random, &available) { + results.push(first); + } + while next_int(random, 50) <= cost { + if let Some((last, _)) = results.last() { + let last = last.clone(); + available.retain(|(e, _)| self.compatible(&last, e)); + } + if available.is_empty() { + break; + } + if let Some(next) = self.weighted(random, &available) { + results.push(next); + } + cost /= 2; + } + } + results + } + + // ---- Effect components ---- + + /// Run `component` value effects of every enchantment on `stack` over `value`. + pub fn modify_value(&self, stack: Option<&ItemStack>, component: &str, ctx: &EffectContext<'_>, random: &mut LegacyRandom, value: f32) -> f32 { + let Some(stack) = stack else { return value }; + let mut value = value; + for (id, level) in stack.enchantments() { + value = self.modify_value_with(id, *level, component, ctx, random, value); + } + value + } + pub fn modify_value_with(&self, id: &str, level: u32, component: &str, ctx: &EffectContext<'_>, random: &mut LegacyRandom, mut value: f32) -> f32 { + let Some(e) = self.get(id) else { return value }; + for effect in e.effects[component].as_array().into_iter().flatten() { + if let Some(req) = effect.get("requirements") + && !self.condition(req, level, ctx, random) + { + continue; + } + value = apply_value_effect(&effect["effect"], level, random, value); + } + value + } + /// Whether `stack` has any enchantment providing `component`. + pub fn has_component(&self, stack: &ItemStack, component: &str) -> bool { + stack.enchantments().iter().any(|(id, _)| self.get(id).is_some_and(|e| e.effects.get(component).is_some())) + } + /// The highest level among enchantments on `stack` that have `component`. + pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 { + stack.enchantments().iter().filter(|(id, _)| self.get(id).is_some_and(|e| e.effects.get(component).is_some())).map(|(_, l)| *l).max().unwrap_or(0) + } + /// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation). + pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> { + let mut out = Vec::new(); + for (id, level) in stack.enchantments() { + let Some(e) = self.get(id) else { continue }; + for a in e.effects["minecraft:attributes"].as_array().into_iter().flatten() { + out.push(( + a["attribute"].as_str().unwrap_or("").to_owned(), + format!("{}.{}", a["id"].as_str().unwrap_or(""), level), + f64::from(level_value(&a["amount"], *level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + )); + } + } + out + } + /// Sum of `add_value` amounts of one attribute from enchantments on `stack`. + pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 { + stack.map_or(0.0, |s| self.attributes(s).iter().filter(|a| a.0 == attribute && a.3 == "add_value").map(|a| a.2).sum()) + } + fn entity_matches(&self, spec: &Value, entity: Option<&str>) -> bool { + let Some(entity) = entity else { return false }; + match spec.as_str() { + Some(s) => match s.strip_prefix('#') { + Some(tag) => self.entity_tags.get(tag).is_some_and(|t| t.contains(entity)), + None => s == entity, + }, + None => string_list(spec).iter().any(|s| s == entity), + } + } + /// The loot-condition subset enchantment `requirements` use. + pub fn condition(&self, c: &Value, level: u32, ctx: &EffectContext<'_>, random: &mut LegacyRandom) -> bool { + match c["type"].as_str().or(c["condition"].as_str()).unwrap_or("") { + "minecraft:inverted" => !self.condition(&c["term"], level, ctx, random), + "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, level, ctx, random)), + "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, level, ctx, random)), + "minecraft:match_tool" => { + let Some(tool) = ctx.tool else { return false }; + let items = &c["predicate"]["items"]; + if items.is_null() { + return true; + } + string_list(items).iter().any(|s| match s.strip_prefix('#') { + Some(tag) => ctx.items.is_some_and(|i| i.item_tags.get(tag).is_some_and(|t| t.contains(tool))), + None => s == tool, + }) + } + "minecraft:damage_source_properties" => { + let p = &c["predicate"]; + if let Some(direct) = p["is_direct"].as_bool() + && direct != ctx.is_direct + { + return false; + } + p["tags"].as_array().into_iter().flatten().all(|t| { + let tag = t["id"].as_str().unwrap_or("").trim_start_matches('#'); + let has = ctx.damage_type.is_some_and(|d| self.damage_tags.get(tag).is_some_and(|s| s.contains(d))); + has == t["expected"].as_bool().unwrap_or(true) + }) + } + "minecraft:entity_properties" => { + let entity = match c["entity"].as_str().unwrap_or("this") { + "this" => ctx.this, + "attacker" => ctx.attacker, + "direct_attacker" => ctx.direct_attacker, + _ => None, + }; + let spec = &c["predicate"]["minecraft:entity_type"]; + let spec = if spec.is_null() { &c["predicate"]["type"] } else { spec }; + spec.is_null() && entity.is_some() || self.entity_matches(spec, entity) + } + "minecraft:random_chance" => { + let chance = match &c["chance"] { + Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("minecraft:enchantment_level") => level_value(&c["chance"]["amount"], level), + v => v.as_f64().map_or_else(|| level_value(v, level), |f| f as f32), + }; + random.next_float() < chance + } + _ => false, + } + } +} +/// What enchantment requirement predicates can see. +#[derive(Clone, Copy, Default)] +pub struct EffectContext<'a> { + pub items: Option<&'a Items>, + /// The tool for `match_tool` (the enchanted item, or the ammo for ammo_use). + pub tool: Option<&'a str>, + /// Damage type id (e.g. `minecraft:fall`). + pub damage_type: Option<&'a str>, + pub is_direct: bool, + /// Entity type ids: the victim/user ("this"), attacker and direct attacker. + pub this: Option<&'a str>, + pub attacker: Option<&'a str>, + pub direct_attacker: Option<&'a str>, +} +fn next_int(random: &mut LegacyRandom, bound: i32) -> i32 { + random.next_int_bound(bound.max(1)).unwrap_or(0) +} +/// `LevelBasedValue.calculate`. +pub fn level_value(v: &Value, level: u32) -> f32 { + let l = level as f32; + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, + Value::Object(o) => { + let f = |k: &str| o.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32; + match o.get("type").and_then(Value::as_str).unwrap_or("") { + "minecraft:linear" => f("base") + f("per_level_above_first") * (l - 1.0), + "minecraft:levels_squared" => l * l + f("added"), + "minecraft:clamped" => level_value(&o["value"], level).clamp(f("min"), f("max")), + "minecraft:fraction" => { + let d = level_value(&o["denominator"], level); + if d == 0.0 { 0.0 } else { level_value(&o["numerator"], level) / d } + } + "minecraft:exponent" => level_value(&o["base"], level).powf(level_value(&o["power"], level)), + "minecraft:lookup" => { + let values = o.get("values").and_then(Value::as_array); + match values.and_then(|a| a.get(level as usize - 1)) { + Some(v) => v.as_f64().unwrap_or(0.0) as f32, + None => level_value(&o["fallback"], level), + } + } + _ => f("value"), + } + } + _ => 0.0, + } +} +/// `EnchantmentValueEffect.process`. +pub fn apply_value_effect(effect: &Value, level: u32, random: &mut LegacyRandom, value: f32) -> f32 { + match effect["type"].as_str().unwrap_or("") { + "minecraft:add" => value + level_value(&effect["value"], level), + "minecraft:multiply" => value * level_value(&effect["factor"], level), + "minecraft:set" => level_value(&effect["value"], level), + "minecraft:remove_binomial" => { + let p = level_value(&effect["chance"], level); + let n = value; + let removed = if !(n <= 128.0) && !(n * p < 20.0) && !(n * (1.0 - p) < 20.0) { + let miu = (f64::from(n) * f64::from(p)).floor(); + let sigma = (f64::from(n) * f64::from(p) * f64::from(1.0 - p)).sqrt(); + ((miu + random.next_gaussian() * sigma).round() as i32).clamp(0, n as i32) + } else { + let mut d = 0; + for _ in 0..n as i32 { + if random.next_float() < p { + d += 1; + } + } + d + }; + n - removed as f32 + } + "minecraft:all_of" => effect["effects"].as_array().into_iter().flatten().fold(value, |v, e| apply_value_effect(e, level, random, v)), + _ => value, + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use serde_json::json; + + /// A small registry built from literal JSON matching the vanilla files. + pub fn sample() -> Enchantments { + let defs = [ + ("minecraft:sharpness", json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}})), + ("minecraft:smite", json!({"anvil_cost":2,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":25,"per_level_above_first":8},"max_level":5,"min_cost":{"base":5,"per_level_above_first":8},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/weapon","weight":5,"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":2.5,"per_level_above_first":2.5}},"requirements":{"type":"minecraft:entity_properties","entity":"this","predicate":{"minecraft:entity_type":"#minecraft:sensitive_to_smite"}}}]}})), + ("minecraft:unbreaking", json!({"anvil_cost":2,"max_cost":{"base":55,"per_level_above_first":8},"max_level":3,"min_cost":{"base":5,"per_level_above_first":8},"supported_items":"#minecraft:enchantable/durability","weight":5,"effects":{"minecraft:item_damage":[{"effect":{"type":"minecraft:remove_binomial","chance":{"type":"minecraft:fraction","denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0},"numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0}}}}]}})), + ("minecraft:mending", json!({"anvil_cost":4,"max_cost":{"base":75,"per_level_above_first":25},"max_level":1,"min_cost":{"base":25,"per_level_above_first":25},"supported_items":"#minecraft:enchantable/durability","weight":2})), + ("minecraft:feather_falling", json!({"anvil_cost":2,"max_cost":{"base":11,"per_level_above_first":6},"max_level":4,"min_cost":{"base":5,"per_level_above_first":6},"supported_items":"#minecraft:enchantable/foot_armor","weight":5,"effects":{"minecraft:damage_protection":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":3.0,"per_level_above_first":3.0}},"requirements":{"type":"minecraft:damage_source_properties","predicate":{"tags":[{"expected":true,"id":"#minecraft:is_fall"},{"expected":false,"id":"#minecraft:bypasses_invulnerability"}]}}}]}})), + ]; + let list: Vec = defs + .iter() + .map(|(id, v)| Enchantment { + id: Arc::from(*id), + description: id.trim_start_matches("minecraft:").into(), + max_level: v["max_level"].as_u64().unwrap() as u32, + weight: v["weight"].as_u64().unwrap() as u32, + anvil_cost: v["anvil_cost"].as_u64().unwrap() as u32, + min_cost: Cost::parse(&v["min_cost"]), + max_cost: Cost::parse(&v["max_cost"]), + supported: string_list(&v["supported_items"]), + primary: v.get("primary_items").map(string_list), + exclusive: if v["exclusive_set"].is_null() { HashSet::new() } else { [Arc::from("minecraft:sharpness"), Arc::from("minecraft:smite")].into_iter().collect() }, + slots: vec![], + effects: v["effects"].clone(), + }) + .collect(); + let index = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + let pool: Vec> = ["minecraft:feather_falling", "minecraft:sharpness", "minecraft:smite", "minecraft:unbreaking", "minecraft:mending"].iter().map(|s| Arc::from(*s)).collect(); + let mut tags = HashMap::new(); + tags.insert("minecraft:in_enchanting_table".to_owned(), pool[..4].to_vec()); + tags.insert("minecraft:tooltip_order".to_owned(), vec![Arc::from("minecraft:sharpness"), Arc::from("minecraft:unbreaking")]); + let mut entity_tags = HashMap::new(); + entity_tags.insert("minecraft:sensitive_to_smite".to_owned(), ["minecraft:zombie".to_owned()].into_iter().collect()); + let mut damage_tags = HashMap::new(); + damage_tags.insert("minecraft:is_fall".to_owned(), ["minecraft:fall".to_owned()].into_iter().collect()); + let mut props = HashMap::new(); + for (item, value) in [("minecraft:diamond_sword", 10), ("minecraft:iron_sword", 14), ("minecraft:book", 1), ("minecraft:iron_boots", 9)] { + props.insert(Arc::from(item), ItemProps { enchantable: value, ..Default::default() }); + } + Enchantments { list, index, tags, entity_tags, damage_tags, props, lang: HashMap::new() } + } + pub fn sample_items() -> Items { + let mut item_tags: HashMap> = HashMap::new(); + let swords = ["minecraft:diamond_sword", "minecraft:iron_sword"]; + for tag in ["enchantable/melee_weapon", "enchantable/sharp_weapon", "enchantable/weapon", "enchantable/durability"] { + item_tags.insert(format!("minecraft:{tag}"), swords.iter().map(|s| (*s).to_owned()).collect()); + } + item_tags.get_mut("minecraft:enchantable/durability").unwrap().insert("minecraft:iron_boots".into()); + item_tags.insert("minecraft:enchantable/foot_armor".into(), ["minecraft:iron_boots".to_owned()].into_iter().collect()); + Items::for_tests(item_tags) + } + + #[test] + fn level_based_values() { + assert_eq!(level_value(&json!({"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}), 5), 3.0); + assert_eq!(level_value(&json!({"type":"minecraft:levels_squared","added":1.0}), 3), 10.0); + assert_eq!(level_value(&json!({"type":"minecraft:fraction","numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0},"denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0}}), 3), 0.75); + assert_eq!(level_name(4), "IV"); + assert_eq!(Cost { base: 1, per_level: 11 }.calculate(5), 45); + } + + #[test] + fn enchanting_cost_matches_vanilla_formula() { + let e = sample(); + // Replays EnchantmentHelper.getEnchantmentCost draws by hand. + for seed in [0i64, 1, 42, -7, 123456] { + for bookcases in [0, 5, 15, 20] { + let mut a = LegacyRandom::new(seed); + let mut b = LegacyRandom::new(seed); + let costs: Vec = (0..3).map(|slot| e.enchantment_cost(&mut a, slot, bookcases, "minecraft:diamond_sword")).collect(); + let bc = bookcases.min(15); + let expect: Vec = (0..3) + .map(|slot| { + let s = b.next_int_bound(8).unwrap() + 1 + (bc >> 1) + b.next_int_bound(bc + 1).unwrap(); + match slot { + 0 => (s / 3).max(1), + 1 => s * 2 / 3 + 1, + _ => s.max(bc * 2), + } + }) + .collect(); + assert_eq!(costs, expect); + assert!(costs[2] <= 30); + } + } + assert_eq!(e.enchantment_cost(&mut LegacyRandom::new(0), 0, 15, "minecraft:stick"), 0); + } + + #[test] + fn selection_respects_costs_and_exclusivity() { + let e = sample(); + let items = sample_items(); + let pool = e.tag("minecraft:in_enchanting_table").to_vec(); + for seed in 0..200 { + let mut r = LegacyRandom::new(seed); + let picked = e.select(&items, &mut r, "minecraft:diamond_sword", 30, &pool); + assert!(!picked.is_empty()); + let has = |id: &str| picked.iter().any(|(p, _)| &**p == id); + assert!(!(has("minecraft:sharpness") && has("minecraft:smite")), "{picked:?}"); + assert!(!has("minecraft:feather_falling")); + for (id, l) in &picked { + assert!(*l >= 1 && *l <= e.get(id).unwrap().max_level); + } + } + // Books accept every enchantment in the pool. + let mut r = LegacyRandom::new(3); + let available = e.available_results(&items, 20, "minecraft:book", &pool); + assert!(available.iter().any(|(id, _)| &**id == "minecraft:feather_falling")); + assert!(e.select(&items, &mut r, "minecraft:stick", 30, &pool).is_empty()); + } + + #[test] + fn value_effects_and_requirements() { + let e = sample(); + let items = sample_items(); + let mut sword = ItemStack::new("minecraft:diamond_sword", 1); + sword.enchant("minecraft:sharpness", 5); + let mut r = LegacyRandom::new(1); + let ctx = EffectContext { items: Some(&items), this: Some("minecraft:zombie"), ..Default::default() }; + assert_eq!(e.modify_value(Some(&sword), "minecraft:damage", &ctx, &mut r, 0.0), 3.0); + let mut smite = ItemStack::new("minecraft:diamond_sword", 1); + smite.enchant("minecraft:smite", 2); + assert_eq!(e.modify_value(Some(&smite), "minecraft:damage", &ctx, &mut r, 0.0), 5.0); + let pig = EffectContext { this: Some("minecraft:pig"), ..ctx }; + assert_eq!(e.modify_value(Some(&smite), "minecraft:damage", &pig, &mut r, 0.0), 0.0); + let mut boots = ItemStack::new("minecraft:iron_boots", 1); + boots.enchant("minecraft:feather_falling", 4); + let fall = EffectContext { damage_type: Some("minecraft:fall"), ..Default::default() }; + assert_eq!(e.modify_value(Some(&boots), "minecraft:damage_protection", &fall, &mut r, 0.0), 12.0); + let lava = EffectContext { damage_type: Some("minecraft:lava"), ..Default::default() }; + assert_eq!(e.modify_value(Some(&boots), "minecraft:damage_protection", &lava, &mut r, 0.0), 0.0); + // Unbreaking III keeps about 1/4 of durability hits. + let mut tool = ItemStack::new("minecraft:diamond_sword", 1); + tool.enchant("minecraft:unbreaking", 3); + let kept: f32 = (0..4000).map(|_| e.modify_value(Some(&tool), "minecraft:item_damage", &ctx, &mut r, 1.0)).sum(); + assert!((800.0..1200.0).contains(&kept), "{kept}"); + } + + #[test] + fn names_and_tooltip_order() { + let e = sample(); + assert_eq!(e.full_name("minecraft:mending", 1).0, "mending"); + assert_eq!(e.full_name("minecraft:sharpness", 1).0, "sharpness I"); + let levels = vec![(Arc::from("minecraft:unbreaking"), 3), (Arc::from("minecraft:mending"), 1), (Arc::from("minecraft:sharpness"), 2)]; + let lines: Vec = e.tooltip(&levels).into_iter().map(|l| l.0).collect(); + assert_eq!(lines, ["sharpness II", "unbreaking III", "mending"]); + assert!(!e.compatible("minecraft:sharpness", "minecraft:smite")); + assert!(e.compatible("minecraft:sharpness", "minecraft:unbreaking")); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6f6b063aa..1e22514fe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -792,11 +792,11 @@ impl Game<'_> { PlayerEffect::OpenMenu => self.open_menu([pos.x, pos.y, pos.z]), PlayerEffect::Sleep => self.try_sleep([pos.x, pos.y, pos.z]), PlayerEffect::GiveItem(item) => { - if let Some(rest) = self.give(ItemStack { item, count: 1, damage: 0 }) { + if let Some(rest) = self.give(ItemStack { item, count: 1, damage: 0, extra: None }) { self.pop_resource([pos.x, pos.y, pos.z], rest); } } - PlayerEffect::DropItem(item) => self.pop_resource([pos.x, pos.y + 1, pos.z], ItemStack { item, count: 1, damage: 0 }), + PlayerEffect::DropItem(item) => self.pop_resource([pos.x, pos.y + 1, pos.z], ItemStack { item, count: 1, damage: 0, extra: None }), PlayerEffect::EatCake => { if let Some(p) = self.player.as_mut() { let food = &mut p.health.food; @@ -861,7 +861,7 @@ impl Game<'_> { if matches!(landing, Landing::Broken) { let item = self.res.facts.get(state).item.clone(); if &*item != "minecraft:air" { - self.pop_resource(pos, ItemStack { item, count: 1, damage: 0 }); + self.pop_resource(pos, ItemStack { item, count: 1, damage: 0, extra: None }); } } } @@ -2895,7 +2895,7 @@ impl Game<'_> { let mut inventory = vec![None; 36]; self.armor = [None, None, None, None]; for (slot, id, count, damage) in &level.inventory { - let stack = ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage }; + let stack = ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage, extra: level.inventory_components.get(slot).cloned() }; if (100..104).contains(slot) { self.armor[usize::from(103 - slot)] = Some(stack); } else if let Some(cell) = inventory.get_mut(usize::from(*slot)) { @@ -2904,7 +2904,7 @@ impl Game<'_> { } if self.creative && level.inventory.is_empty() && level.position.is_none() { for (i, name) in ["minecraft:grass_block", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass", "minecraft:torch", "minecraft:oak_log", "minecraft:chest", "minecraft:furnace", "minecraft:diamond_pickaxe"].iter().enumerate() { - inventory[i] = Some(ItemStack { item: Arc::from(*name), count: 1, damage: 0 }); + inventory[i] = Some(ItemStack { item: Arc::from(*name), count: 1, damage: 0, extra: None }); } } let (yaw, pitch) = self.options.look.unwrap_or((level.rotation[0], level.rotation[1])); @@ -3350,7 +3350,7 @@ impl Game<'_> { self.audio.play(sound, Some(at(hit.pos)), 1.0, 1.0); if !self.creative { self.consume_held(); - let filled = ItemStack { item: Arc::from(filled), count: 1, damage: 0 }; + let filled = ItemStack { item: Arc::from(filled), count: 1, damage: 0, extra: None }; if self.inventory[self.selected].is_none() { self.inventory[self.selected] = Some(filled); } else if let Some(rest) = self.give(filled) @@ -3376,7 +3376,7 @@ impl Game<'_> { let sound = if item == "water_bucket" { "minecraft:item.bucket.empty" } else { "minecraft:item.bucket.empty_lava" }; self.audio.play(sound, Some(at(target)), 1.0, 1.0); if !self.creative { - self.inventory[self.selected] = Some(ItemStack { item: Arc::from("minecraft:bucket"), count: 1, damage: 0 }); + self.inventory[self.selected] = Some(ItemStack { item: Arc::from("minecraft:bucket"), count: 1, damage: 0, extra: None }); } return Ok(true); } @@ -3390,7 +3390,7 @@ impl Game<'_> { if let Some(result) = result { self.set_state_named(hit.pos, result, &[])?; if name == "rooted_dirt" { - self.pop_resource([hit.pos[0], hit.pos[1] - 1, hit.pos[2]], ItemStack { item: Arc::from("minecraft:hanging_roots"), count: 1, damage: 0 }); + self.pop_resource([hit.pos[0], hit.pos[1] - 1, hit.pos[2]], ItemStack { item: Arc::from("minecraft:hanging_roots"), count: 1, damage: 0, extra: None }); } self.audio.play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0); self.damage_held(1); @@ -3961,7 +3961,7 @@ impl Game<'_> { batch.sprite(&self.res.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); - let stack = ItemStack { item: Arc::from(t.icon.as_str()), count: 1, damage: 0 }; + let stack = ItemStack { item: Arc::from(t.icon.as_str()), count: 1, damage: 0, extra: None }; self.draw_item(batch, &stack, ox + tx + 5.0, oy + ty + if t.top { 9.0 } else { 7.0 }); } let atlas = &self.res.atlas; @@ -3977,7 +3977,7 @@ impl Game<'_> { for c in 0..9 { let Some(item) = items.get((first + r) * 9 + c) else { continue }; let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); - let stack = ItemStack { item: Arc::from(item.as_str()), count: 1, damage: 0 }; + let stack = ItemStack { item: Arc::from(item.as_str()), count: 1, damage: 0, extra: None }; self.draw_item(batch, &stack, x, y); if self.cursor.0 >= x && self.cursor.0 < x + 16.0 && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); @@ -4051,7 +4051,7 @@ impl Game<'_> { } let Some(item) = items.get((first + r) * 9 + c) else { return }; let max = self.res.items.get(item).map_or(64, |i| i.max_stack); - let stack = ItemStack { item: Arc::from(item.as_str()), count: if right { 1 } else { max }, damage: 0 }; + let stack = ItemStack { item: Arc::from(item.as_str()), count: if right { 1 } else { max }, damage: 0, extra: None }; if shift { let _ = self.give(stack); } else { @@ -4102,10 +4102,14 @@ impl Game<'_> { .enumerate() .filter_map(|(i, s)| s.as_ref().map(|s| (i as u8, s.item.to_string(), s.count, s.damage))) .collect(); + level.inventory_components = self.inventory.iter().enumerate().filter_map(|(i, s)| Some((i as u8, s.as_ref()?.extra.clone()?))).collect(); // Vanilla stores armor in slots 100 (feet) to 103 (head). for (i, s) in self.armor.iter().enumerate() { if let Some(s) = s { level.inventory.push((103 - i as u8, s.item.to_string(), s.count, s.damage)); + if let Some(extra) = s.extra.clone() { + level.inventory_components.insert(103 - i as u8, extra); + } } } level.dimension = self.dim.id().to_owned(); @@ -4299,7 +4303,7 @@ impl Game<'_> { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let item = self.res.facts.get(state).item.clone(); if &*item != "minecraft:air" { - self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0 }); + self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0, extra: None }); } } } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f6b2bdcc6..f645f4a8f 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -174,6 +174,7 @@ impl Game<'_> { item: item.as_str().into(), count: n, damage: 0, + extra: None, }) .map_or(0, |r| r.count); given += n - rest; diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs new file mode 100644 index 000000000..7eb995762 --- /dev/null +++ b/crates/horizon-client/src/item_data.rs @@ -0,0 +1,261 @@ +//! Item stack components beyond count and damage: enchantments, stored +//! (book) enchantments, `repair_cost`, `custom_name`, `potion_contents` and +//! `trim`, with their NBT form in vanilla's `components` compound. +use crate::items::ItemStack; +use horizon_world::nbt::{JavaString, Tag}; +use std::sync::Arc; + +/// Enchantment id and level, in insertion order. +pub type Levels = Vec<(Arc, u32)>; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StackData { + /// `minecraft:enchantments`. + pub enchantments: Levels, + /// `minecraft:stored_enchantments` (enchanted books). + pub stored_enchantments: Levels, + /// `minecraft:repair_cost` (anvil prior-work penalty). + pub repair_cost: u32, + /// `minecraft:custom_name` as plain text. + pub custom_name: Option, + /// `minecraft:potion_contents.potion`. + pub potion: Option>, + /// `minecraft:trim`: (material, pattern). + pub trim: Option<(Arc, Arc)>, +} +impl StackData { + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} + +impl ItemStack { + pub fn new(item: &str, count: u32) -> Self { + Self { item: Arc::from(item), count, damage: 0, extra: None } + } + pub fn data(&self) -> Option<&StackData> { + self.extra.as_deref() + } + pub fn data_mut(&mut self) -> &mut StackData { + self.extra.get_or_insert_with(Box::default) + } + /// Drops an all-default component box so equal stacks compare equal. + pub fn tidy(&mut self) { + if self.extra.as_ref().is_some_and(|d| d.is_empty()) { + self.extra = None; + } + } + pub fn enchantments(&self) -> &[(Arc, u32)] { + self.data().map_or(&[], |d| &d.enchantments) + } + pub fn stored_enchantments(&self) -> &[(Arc, u32)] { + self.data().map_or(&[], |d| &d.stored_enchantments) + } + /// `EnchantmentHelper.getItemEnchantmentLevel` (0 when absent). + pub fn enchantment_level(&self, id: &str) -> u32 { + self.enchantments().iter().find(|(e, _)| &**e == id).map_or(0, |(_, l)| *l) + } + /// The component an anvil/grindstone works on: stored for books. + pub fn crafting_enchantments(&self) -> &[(Arc, u32)] { + if &*self.item == "minecraft:enchanted_book" { self.stored_enchantments() } else { self.enchantments() } + } + pub fn set_crafting_enchantments(&mut self, levels: Levels) { + if &*self.item == "minecraft:enchanted_book" { + self.data_mut().stored_enchantments = levels; + } else { + self.data_mut().enchantments = levels; + } + self.tidy(); + } + /// `ItemStack.enchant`: upgrade to the higher level. + pub fn enchant(&mut self, id: &str, level: u32) { + let book = &*self.item == "minecraft:enchanted_book"; + let data = self.data_mut(); + let list = if book { &mut data.stored_enchantments } else { &mut data.enchantments }; + upgrade(list, id, level); + } + pub fn has_any_enchantments(&self) -> bool { + !self.enchantments().is_empty() || !self.stored_enchantments().is_empty() + } + pub fn repair_cost(&self) -> u32 { + self.data().map_or(0, |d| d.repair_cost) + } + pub fn custom_name(&self) -> Option<&str> { + self.data().and_then(|d| d.custom_name.as_deref()) + } + pub fn potion(&self) -> Option<&str> { + self.data().and_then(|d| d.potion.as_deref()) + } + pub fn with_potion(mut self, potion: &str) -> Self { + self.data_mut().potion = Some(Arc::from(potion)); + self + } + /// `ItemStack.isSameItemSameComponents`. + pub fn same_item_same_components(&self, other: &Self) -> bool { + self.item == other.item && self.damage == other.damage && self.data() == other.data() + } + /// `ItemStack.transmuteCopy`: another item keeping every component. + pub fn transmute(&self, item: &str, count: u32) -> Self { + let mut stack = Self { item: Arc::from(item), count, ..self.clone() }; + stack.tidy(); + stack + } +} +/// `ItemEnchantments.Mutable.upgrade`. +pub fn upgrade(list: &mut Levels, id: &str, level: u32) { + if level == 0 { + return; + } + match list.iter_mut().find(|(e, _)| &**e == id) { + Some((_, l)) => *l = (*l).max(level), + None => list.push((Arc::from(id), level)), + } +} +/// `ItemEnchantments.Mutable.set` (level 0 removes). +pub fn set_level(list: &mut Levels, id: &str, level: u32) { + if level == 0 { + list.retain(|(e, _)| &**e != id); + } else { + match list.iter_mut().find(|(e, _)| &**e == id) { + Some((_, l)) => *l = level, + None => list.push((Arc::from(id), level)), + } + } +} + +fn levels_tag(levels: &Levels) -> Tag { + Tag::compound(levels.iter().map(|(id, l)| (&**id, Tag::Int(*l as i32)))) +} +fn int(t: &Tag) -> Option { + match t { + Tag::Byte(v) => Some(i64::from(*v)), + Tag::Short(v) => Some(i64::from(*v)), + Tag::Int(v) => Some(i64::from(*v)), + Tag::Long(v) => Some(*v), + _ => None, + } +} +fn string(t: &Tag) -> Option { + match t { + Tag::String(s) => Some(s.to_string_lossy()), + _ => None, + } +} +fn read_levels(t: Option<&Tag>) -> Levels { + let Some(Tag::Compound(map)) = t else { return Vec::new() }; + // Pre-1.21.5 worlds wrap the map in {levels: {...}}. + if let Some(Tag::Compound(inner)) = map.get(&JavaString::from("levels")) { + return inner.iter().filter_map(|(k, v)| Some((Arc::from(k.to_string_lossy().as_str()), int(v)?.clamp(1, 255) as u32))).collect(); + } + map.iter().filter_map(|(k, v)| Some((Arc::from(k.to_string_lossy().as_str()), int(v)?.clamp(1, 255) as u32))).collect() +} +/// A text component as stored by vanilla: a plain string or `{"text": ...}`. +fn read_text(t: &Tag) -> Option { + match t { + Tag::String(s) => Some(s.to_string_lossy()), + Tag::Compound(_) => t.get("text").and_then(string), + _ => None, + } +} + +/// The `components` compound for a stack, or None when every component is default. +pub fn encode_components(stack: &ItemStack) -> Option { + components_tag(stack.damage, stack.data()) +} +/// `encode_components` from the damage value and extra components. +pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { + let mut entries: Vec<(&str, Tag)> = Vec::new(); + if damage > 0 { + entries.push(("minecraft:damage", Tag::Int(damage as i32))); + } + if let Some(d) = data { + if !d.enchantments.is_empty() { + entries.push(("minecraft:enchantments", levels_tag(&d.enchantments))); + } + if !d.stored_enchantments.is_empty() { + entries.push(("minecraft:stored_enchantments", levels_tag(&d.stored_enchantments))); + } + if d.repair_cost > 0 { + entries.push(("minecraft:repair_cost", Tag::Int(d.repair_cost as i32))); + } + if let Some(name) = &d.custom_name { + entries.push(("minecraft:custom_name", Tag::String(name.as_str().into()))); + } + if let Some(potion) = &d.potion { + entries.push(("minecraft:potion_contents", Tag::compound([("potion", Tag::String((&**potion).into()))]))); + } + if let Some((material, pattern)) = &d.trim { + entries.push(( + "minecraft:trim", + Tag::compound([("material", Tag::String((&**material).into())), ("pattern", Tag::String((&**pattern).into()))]), + )); + } + } + (!entries.is_empty()).then(|| Tag::compound(entries)) +} +/// Damage and extra components from a stack's `components` compound. +pub fn decode_components(components: Option<&Tag>) -> (u32, Option>) { + let Some(c) = components else { return (0, None) }; + let damage = c.get("minecraft:damage").and_then(int).unwrap_or(0).max(0) as u32; + let potion = match c.get("minecraft:potion_contents") { + Some(Tag::String(s)) => Some(Arc::from(s.to_string_lossy().as_str())), + Some(t) => t.get("potion").and_then(string).map(|s| Arc::from(s.as_str())), + None => None, + }; + let data = StackData { + enchantments: read_levels(c.get("minecraft:enchantments")), + stored_enchantments: read_levels(c.get("minecraft:stored_enchantments")), + repair_cost: c.get("minecraft:repair_cost").and_then(int).unwrap_or(0).max(0) as u32, + custom_name: c.get("minecraft:custom_name").and_then(read_text), + potion, + trim: c.get("minecraft:trim").and_then(|t| { + Some((Arc::from(t.get("material").and_then(string)?.as_str()), Arc::from(t.get("pattern").and_then(string)?.as_str()))) + }), + }; + (damage, (!data.is_empty()).then(|| Box::new(data))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn components_round_trip() { + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + stack.damage = 12; + stack.enchant("minecraft:sharpness", 3); + stack.enchant("minecraft:unbreaking", 2); + stack.data_mut().repair_cost = 3; + stack.data_mut().custom_name = Some("Blade".into()); + let tag = encode_components(&stack).expect("components"); + let (damage, extra) = decode_components(Some(&tag)); + assert_eq!(damage, 12); + let back = ItemStack { damage, extra, ..ItemStack::new("minecraft:diamond_sword", 1) }; + assert_eq!(back.enchantment_level("minecraft:sharpness"), 3); + assert_eq!(back.enchantment_level("minecraft:unbreaking"), 2); + assert_eq!(back.repair_cost(), 3); + assert_eq!(back.custom_name(), Some("Blade")); + } + + #[test] + fn plain_stacks_have_no_components() { + let stack = ItemStack::new("minecraft:stone", 64); + assert!(encode_components(&stack).is_none()); + let mut named = stack.clone(); + named.data_mut(); + named.tidy(); + assert_eq!(named, stack); + } + + #[test] + fn books_store_enchantments() { + let mut book = ItemStack::new("minecraft:enchanted_book", 1); + book.enchant("minecraft:mending", 1); + assert!(book.enchantments().is_empty()); + assert_eq!(book.stored_enchantments().len(), 1); + upgrade(&mut book.data_mut().stored_enchantments, "minecraft:mending", 1); + assert_eq!(book.crafting_enchantments()[0].1, 1); + let book = ItemStack::new("minecraft:book", 1).transmute("minecraft:enchanted_book", 1); + assert!(book.extra.is_none()); + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 3caf4b445..45aea62db 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -45,6 +45,8 @@ pub struct ItemStack { pub item: Arc, pub count: u32, pub damage: u32, + /// Components beyond count and damage (see `item_data`); None when default. + pub extra: Option>, } pub struct Items { pub items: HashMap, ItemInfo>, @@ -206,6 +208,11 @@ impl Items { pub fn get(&self, id: &str) -> Option<&ItemInfo> { self.items.get(id) } + /// An item table with only tags, for unit tests of item rules. + #[cfg(test)] + pub fn for_tests(item_tags: HashMap>) -> Self { + Self { items: HashMap::new(), order: Vec::new(), block_tags: HashMap::new(), item_tags, loot: HashMap::new() } + } fn block_matches(&self, spec: &str, block: &str) -> bool { match spec.strip_prefix('#') { Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)), @@ -438,6 +445,7 @@ impl LootContext<'_> { item: Arc::from(e["name"].as_str().unwrap_or("minecraft:air")), count: 1, damage: 0, + extra: None, }, e["modifier"].clone(), )); @@ -466,7 +474,7 @@ impl LootContext<'_> { true } "minecraft:empty" => { - out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0 }, Value::Null)); + out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0, extra: None }, Value::Null)); true } _ => false, diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 00265cade..ece00a7ee 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -11,6 +11,7 @@ pub mod clock; pub mod containers; pub mod control; pub mod crafting; +pub mod enchant; pub mod creative; pub mod collisions; pub mod entities; @@ -20,6 +21,7 @@ pub mod health; pub mod hud; pub mod hunger; pub mod input; +pub mod item_data; pub mod items; pub mod landing; pub mod light; @@ -33,6 +35,7 @@ pub mod save; pub mod settings; pub mod sprint; pub mod sprites; +pub mod stations; pub mod streaming; pub mod testgen; pub mod title; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 6997be4f8..6c82a1b28 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -62,8 +62,8 @@ fn encode_items(slots: &[Option]) -> Tag { ("id", string(&s.item)), ("count", Tag::Int(s.count as i32)), ]; - if s.damage > 0 { - entries.push(("components", Tag::compound([("minecraft:damage", Tag::Int(s.damage as i32))]))); + if let Some(components) = crate::item_data::encode_components(s) { + entries.push(("components", components)); } Some(Tag::compound(entries)) }) @@ -81,12 +81,9 @@ fn decode_items(tag: Option<&Tag>, size: usize) -> Vec *c as u32, _ => 1, }; - let damage = match it.get("components").and_then(|c| c.get("minecraft:damage")) { - Some(Tag::Int(d)) => *d as u32, - _ => 0, - }; + let (damage, extra) = crate::item_data::decode_components(it.get("components")); if let Some(cell) = slots.get_mut(*slot as u8 as usize) { - *cell = Some(crate::items::ItemStack { item: Arc::from(id.to_string_lossy().as_str()), count, damage }); + *cell = Some(crate::items::ItemStack { item: Arc::from(id.to_string_lossy().as_str()), count, damage, extra }); } } } @@ -362,6 +359,10 @@ pub struct Level { pub food: i32, pub saturation: f32, pub inventory: Vec<(u8, String, u32, u32)>, + /// Extra item components of `inventory` entries, by slot. + pub inventory_components: HashMap>, + /// Player.XpSeed: the enchanting table seed. + pub xp_seed: i32, pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, @@ -392,6 +393,7 @@ impl Level { let player = data.get("Player"); let float = |t: Option<&Tag>| if let Some(Tag::Float(b)) = t { f32::from_bits(*b) } else { 0.0 }; let mut inventory = Vec::new(); + let mut inventory_components = HashMap::new(); if let Some(Tag::List(items)) = player.and_then(|p| p.get("Inventory")) { for it in items { let slot = if let Some(Tag::Byte(s)) = it.get("Slot") { *s as u8 } else { continue }; @@ -401,6 +403,9 @@ impl Level { .get("components") .and_then(|c| c.get("minecraft:damage")) .map_or(0, |d| long(Some(d)) as u32); + if let (_, Some(extra)) = crate::item_data::decode_components(it.get("components")) { + inventory_components.insert(slot, extra); + } inventory.push((slot, id, count, damage)); } } @@ -439,7 +444,9 @@ impl Level { xp_level: player.map_or(0, |p| long(p.get("XpLevel")) as i32), xp_progress: player.map_or(0.0, |p| float(p.get("XpP"))), xp_total: player.map_or(0, |p| long(p.get("XpTotal")) as i32), + xp_seed: player.map_or(0, |p| long(p.get("XpSeed")) as i32), inventory, + inventory_components, }) } pub fn write(&self, dir: &Path) -> Result<()> { @@ -452,6 +459,7 @@ impl Level { ("XpLevel", Tag::Int(self.xp_level)), ("XpP", Tag::Float(self.xp_progress.to_bits())), ("XpTotal", Tag::Int(self.xp_total)), + ("XpSeed", Tag::Int(self.xp_seed)), ("playerGameType", Tag::Int(i32::from(self.creative))), ( "Rotation", @@ -468,8 +476,8 @@ impl Level { ("id", string(id)), ("count", Tag::Int(*count as i32)), ]; - if *damage > 0 { - entries.push(("components", Tag::compound([("minecraft:damage", Tag::Int(*damage as i32))]))); + if let Some(components) = crate::item_data::components_tag(*damage, self.inventory_components.get(slot).map(|d| &**d)) { + entries.push(("components", components)); } Tag::compound(entries) }) diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs new file mode 100644 index 000000000..9eabd9df8 --- /dev/null +++ b/crates/horizon-client/src/stations.rs @@ -0,0 +1,572 @@ +//! Result rules of the workstation menus, ported from vanilla's +//! `EnchantmentMenu`, `AnvilMenu`, `GrindstoneMenu`, `SmithingMenu` (with +//! `SmithingTransformRecipe` / `SmithingTrimRecipe`) and `StonecutterMenu`. +//! Rendering and clicks live in the game; this module is pure item logic. +use crate::{ + crafting::Ingredient, + enchant::Enchantments, + item_data::{self, Levels}, + items::{ItemStack, Items}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use serde_json::Value; +use std::{collections::HashSet, fs, path::Path, sync::Arc}; + +// ---------------------------------------------------------------- enchanting + +/// `EnchantingTableBlock.BOOKSHELF_OFFSETS`: the 5x5 ring two blocks out, two high. +pub fn bookshelf_offsets() -> Vec<[i32; 3]> { + let mut v = Vec::new(); + for x in -2i32..=2 { + for z in -2i32..=2 { + if x.abs() == 2 || z.abs() == 2 { + for y in 0..=1 { + v.push([x, y, z]); + } + } + } + } + v +} +/// The three offers of `EnchantmentMenu.slotsChanged`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EnchantOffers { + pub costs: [i32; 3], + /// Shown clue: enchantment and level (`enchantClue` / `levelClue`). + pub clues: [Option<(Arc, u32)>; 3], +} +/// `EnchantmentMenu.getEnchantmentList`. +pub fn enchantment_list(e: &Enchantments, items: &Items, seed: i32, slot: usize, cost: i32, item: &str) -> Levels { + let mut random = LegacyRandom::new(i64::from(seed.wrapping_add(slot as i32))); + let pool = e.tag("minecraft:in_enchanting_table").to_vec(); + let mut list = e.select(items, &mut random, item, cost, &pool); + if item == "minecraft:book" && list.len() > 1 { + let i = random.next_int_bound(list.len() as i32).unwrap_or(0) as usize; + list.remove(i); + } + list +} +/// `EnchantmentMenu.slotsChanged` for an enchantable item. +pub fn enchant_offers(e: &Enchantments, items: &Items, seed: i32, bookcases: i32, stack: Option<&ItemStack>) -> EnchantOffers { + let mut offers = EnchantOffers::default(); + let Some(stack) = stack else { return offers }; + // ItemStack.isEnchantable: enchantable component and no enchantments yet. + if e.enchantable(&stack.item) == 0 || !stack.enchantments().is_empty() { + return offers; + } + let mut random = LegacyRandom::new(i64::from(seed)); + for i in 0..3 { + offers.costs[i] = e.enchantment_cost(&mut random, i, bookcases, &stack.item); + if offers.costs[i] < i as i32 + 1 { + offers.costs[i] = 0; + } + } + for i in 0..3 { + if offers.costs[i] > 0 { + // getEnchantmentList reseeds the menu random; the clue draws continue from it. + let mut list_random = LegacyRandom::new(i64::from(seed.wrapping_add(i as i32))); + let pool = e.tag("minecraft:in_enchanting_table").to_vec(); + let mut list = e.select(items, &mut list_random, &stack.item, offers.costs[i], &pool); + if &*stack.item == "minecraft:book" && list.len() > 1 { + let r = list_random.next_int_bound(list.len() as i32).unwrap_or(0) as usize; + list.remove(r); + } + if !list.is_empty() { + let pick = list_random.next_int_bound(list.len() as i32).unwrap_or(0) as usize; + offers.clues[i] = Some(list[pick].clone()); + } + } + } + offers +} +/// `EnchantmentMenu.clickMenuButton` result: the enchanted item, or None. +pub fn apply_enchantment(e: &Enchantments, items: &Items, seed: i32, slot: usize, cost: i32, stack: &ItemStack) -> Option { + let list = enchantment_list(e, items, seed, slot, cost, &stack.item); + if list.is_empty() { + return None; + } + let mut out = if &*stack.item == "minecraft:book" { stack.transmute("minecraft:enchanted_book", stack.count) } else { stack.clone() }; + for (id, level) in list { + out.enchant(&id, level); + } + Some(out) +} + +// ---------------------------------------------------------------- anvil + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AnvilResult { + pub result: Option, + /// Level cost (the `cost` data slot). + pub cost: i32, + /// Material items consumed from the second slot on take. + pub repair_item_count_cost: u32, + pub only_renaming: bool, +} +pub fn is_damageable(items: &Items, stack: &ItemStack) -> bool { + items.get(&stack.item).is_some_and(|i| i.max_damage > 0) +} +fn max_damage(items: &Items, stack: &ItemStack) -> i32 { + items.get(&stack.item).map_or(0, |i| i.max_damage as i32) +} +/// `ItemStack.isValidRepairItem`. +pub fn is_valid_repair_item(e: &Enchantments, items: &Items, stack: &ItemStack, material: &ItemStack) -> bool { + e.props(&stack.item).is_some_and(|p| Enchantments::item_in(items, &p.repairable, &material.item)) +} +/// `AnvilMenu.calculateIncreasedRepairCost`. +pub fn increased_repair_cost(cost: u32) -> u32 { + (u64::from(cost) * 2 + 1).min(i32::MAX as u64) as u32 +} +/// The display name the rename box starts with (`getHoverName`). +pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String { + stack.custom_name().map_or_else(|| names(&stack.item), str::to_owned) +} +/// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched). +pub fn anvil_result( + e: &Enchantments, + items: &Items, + input: Option<&ItemStack>, + addition: Option<&ItemStack>, + name: Option<&str>, + hover_name: &str, + creative: bool, +) -> AnvilResult { + let fail = AnvilResult::default(); + let Some(input) = input else { return fail }; + // EnchantmentHelper.canStoreEnchantments: enchantable or enchanted book... every + // item with an enchantments component, which is all of them in 26.3. + let mut result = input.clone(); + let mut enchantments: Levels = input.crafting_enchantments().to_vec(); + let mut price: i64 = 0; + let tax: i64 = i64::from(input.repair_cost()) + i64::from(addition.map_or(0, ItemStack::repair_cost)); + let mut repair_item_count_cost = 0; + let mut naming_cost = 0; + if let Some(addition) = addition { + // addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component. + let using_book = &*addition.item == "minecraft:enchanted_book"; + if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) { + let max = max_damage(items, &result); + let mut repair = (result.damage as i32).min(max / 4); + if repair <= 0 { + return fail; + } + let mut count = 0; + while repair > 0 && count < addition.count { + result.damage = (result.damage as i32 - repair) as u32; + price += 1; + repair = (result.damage as i32).min(max / 4); + count += 1; + } + repair_item_count_cost = count; + } else { + if !using_book && (result.item != addition.item || !is_damageable(items, &result)) { + return fail; + } + if is_damageable(items, &result) && !using_book { + let max = max_damage(items, &result); + let remaining1 = max - input.damage as i32; + let remaining2 = max_damage(items, addition) - addition.damage as i32; + let additional = remaining2 + max * 12 / 100; + let remaining = remaining1 + additional; + let damage = (max - remaining).max(0); + if damage < result.damage as i32 { + result.damage = damage as u32; + price += 2; + } + } + let mut any_compatible = false; + let mut any_incompatible = false; + for (id, level) in addition.crafting_enchantments() { + let current = enchantments.iter().find(|(x, _)| x == id).map_or(0, |(_, l)| *l); + let mut level = if current == *level { level + 1 } else { (*level).max(current) }; + let Some(def) = e.get(id) else { continue }; + let mut compatible = e.can_enchant(items, id, &input.item); + if creative || &*input.item == "minecraft:enchanted_book" { + compatible = true; + } + for (other, _) in &enchantments { + if other != id && !e.compatible(id, other) { + compatible = false; + price += 1; + } + } + if !compatible { + any_incompatible = true; + } else { + any_compatible = true; + level = level.min(def.max_level); + item_data::set_level(&mut enchantments, id, level); + let mut fee = def.anvil_cost as i64; + if using_book { + fee = (fee / 2).max(1); + } + price += fee * i64::from(level); + if input.count > 1 { + price = 40; + } + } + } + if any_incompatible && !any_compatible { + return fail; + } + } + } + match name { + Some(n) if !n.trim().is_empty() => { + if n != hover_name { + naming_cost = 1; + price += 1; + result.data_mut().custom_name = Some(n.to_owned()); + } + } + _ => { + if input.custom_name().is_some() { + naming_cost = 1; + price += 1; + result.data_mut().custom_name = None; + } + } + } + let mut cost = if price <= 0 { 0 } else { (tax + price).clamp(0, i64::from(i32::MAX)) as i32 }; + let mut out = (price > 0).then_some(result); + let mut only_renaming = false; + if naming_cost == price && naming_cost > 0 { + if cost >= 40 { + cost = 39; + } + only_renaming = true; + } + if cost >= 40 && !creative { + out = None; + } + if let Some(r) = out.as_mut() { + let mut base = r.repair_cost().max(addition.map_or(0, ItemStack::repair_cost)); + if naming_cost != price || naming_cost == 0 { + base = increased_repair_cost(base); + } + r.data_mut().repair_cost = base; + r.set_crafting_enchantments(enchantments); + r.tidy(); + } + AnvilResult { result: out, cost, repair_item_count_cost, only_renaming } +} + +// ---------------------------------------------------------------- grindstone + +/// `GrindstoneMenu` slot filter: damageable or enchanted. +pub fn grindstone_accepts(items: &Items, stack: &ItemStack) -> bool { + is_damageable(items, stack) || stack.has_any_enchantments() +} +fn remove_non_curses(e: &Enchantments, mut item: ItemStack) -> ItemStack { + let kept: Levels = item.crafting_enchantments().iter().filter(|(id, _)| e.is_curse(id)).cloned().collect(); + let n = kept.len(); + item.set_crafting_enchantments(kept); + if &*item.item == "minecraft:enchanted_book" && item.stored_enchantments().is_empty() { + item = item.transmute("minecraft:book", item.count); + } + let mut cost = 0; + for _ in 0..n { + cost = increased_repair_cost(cost); + } + item.data_mut().repair_cost = cost; + item.tidy(); + item +} +/// `GrindstoneMenu.computeResult`. +pub fn grindstone_result(e: &Enchantments, items: &Items, input: Option<&ItemStack>, additional: Option<&ItemStack>) -> Option { + if input.is_none() && additional.is_none() { + return None; + } + if input.is_some_and(|s| s.count > 1) || additional.is_some_and(|s| s.count > 1) { + return None; + } + match (input, additional) { + (Some(a), Some(b)) => { + if a.item != b.item { + return None; + } + let durability = max_damage(items, a).max(max_damage(items, b)); + let remaining = (max_damage(items, a) - a.damage as i32) + (max_damage(items, b) - b.damage as i32) + durability * 5 / 100; + let mut count = 1; + if !is_damageable(items, a) { + let stack_max = items.get(&a.item).map_or(64, |i| i.max_stack); + if stack_max < 2 || a != b { + return None; + } + count = 2; + } + let mut out = ItemStack { count, ..a.clone() }; + if is_damageable(items, &out) { + out.damage = (durability - remaining).max(0) as u32; + } + // mergeEnchantsFrom + let mut levels = out.crafting_enchantments().to_vec(); + for (id, l) in b.crafting_enchantments() { + if !e.is_curse(id) || !levels.iter().any(|(x, _)| x == id) { + item_data::upgrade(&mut levels, id, *l); + } + } + out.set_crafting_enchantments(levels); + Some(remove_non_curses(e, out)) + } + (Some(s), None) | (None, Some(s)) => s.has_any_enchantments().then(|| remove_non_curses(e, s.clone())), + (None, None) => None, + } +} +/// Experience from the grindstone result slot's `getExperienceAmount`. +pub fn grindstone_experience(e: &Enchantments, random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>) -> u32 { + let from = |s: Option<&ItemStack>| -> i32 { + s.map_or(0, |s| { + s.crafting_enchantments().iter().filter(|(id, _)| !e.is_curse(id)).map(|(id, l)| e.get(id).map_or(0, |d| d.min_cost.calculate(*l))).sum() + }) + }; + let amount = from(input) + from(additional); + if amount > 0 { + let half = (f64::from(amount) / 2.0).ceil() as i32; + (half + random.next_int_bound(half).unwrap_or(0)) as u32 + } else { + 0 + } +} + +// ---------------------------------------------------------------- smithing & stonecutting + +#[derive(Clone, Debug)] +pub enum Smithing { + Transform { template: Ingredient, base: Ingredient, addition: Ingredient, result: String }, + Trim { template: Ingredient, base: Ingredient, addition: Ingredient, pattern: String }, +} +#[derive(Clone, Debug)] +pub struct Stonecutting { + pub id: String, + pub input: Ingredient, + pub result: ItemStack, +} +pub struct StationRecipes { + pub smithing: Vec, + /// Sorted by recipe id, the registry order vanilla lists them in. + pub stonecutting: Vec, + /// `trim_material` registry: id -> (asset name, description). + pub trim_materials: Vec<(String, String)>, +} +fn ingredient(v: &Value, items: &Items) -> Ingredient { + let mut set = HashSet::new(); + for s in match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect(), + _ => vec![], + } { + match s.strip_prefix('#') { + Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()), + None => { + set.insert(s); + } + } + } + Ingredient(set) +} +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(); + let mut smithing = Vec::new(); + let mut stonecutting = Vec::new(); + for 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:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")); + match v["type"].as_str().unwrap_or("") { + "minecraft:smithing_transform" => smithing.push(Smithing::Transform { + template: ingredient(&v["template"], items), + base: ingredient(&v["base"], items), + addition: ingredient(&v["addition"], items), + result: v["result"]["id"].as_str().unwrap_or("minecraft:air").to_owned(), + }), + "minecraft:smithing_trim" => smithing.push(Smithing::Trim { + template: ingredient(&v["template"], items), + base: ingredient(&v["base"], items), + addition: ingredient(&v["addition"], items), + pattern: v["pattern"].as_str().unwrap_or("").to_owned(), + }), + "minecraft:stonecutting" => stonecutting.push(Stonecutting { + id, + input: ingredient(&v["ingredient"], items), + result: ItemStack::new(v["result"]["id"].as_str().unwrap_or("minecraft:air"), v["result"]["count"].as_u64().unwrap_or(1) as u32), + }), + _ => {} + } + } + let mut trim_materials = Vec::new(); + let mut tm: Vec<_> = fs::read_dir(root.join("data/minecraft/trim_material")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + tm.sort(); + for p in tm { + if let Ok(bytes) = fs::read(&p) + && let Ok(v) = serde_json::from_slice::(&bytes) + { + let id = format!("minecraft:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")); + trim_materials.push((id, v["description"]["translate"].as_str().unwrap_or("").to_owned())); + } + } + Self { smithing, stonecutting, trim_materials } + } + /// Recipes whose input accepts `stack`, in display order. + pub fn stonecutter(&self, stack: &ItemStack) -> Vec<&Stonecutting> { + self.stonecutting.iter().filter(|r| r.input.test(stack)).collect() + } + fn slot_ok(&self, slot: usize, stack: &ItemStack) -> bool { + self.smithing.iter().any(|r| { + let (t, b, a) = match r { + Smithing::Transform { template, base, addition, .. } | Smithing::Trim { template, base, addition, .. } => (template, base, addition), + }; + [t, b, a][slot].test(stack) + }) + } + /// `RecipePropertySet` SMITHING_TEMPLATE / BASE / ADDITION. + pub fn smithing_accepts(&self, slot: usize, stack: &ItemStack) -> bool { + slot < 3 && self.slot_ok(slot, stack) + } + /// `SmithingMenu.createResult`. + pub fn smithing_result(&self, e: &Enchantments, template: Option<&ItemStack>, base: Option<&ItemStack>, addition: Option<&ItemStack>) -> Option { + let (template, base, addition) = (template?, base?, addition?); + for r in &self.smithing { + match r { + Smithing::Transform { template: t, base: b, addition: a, result } => { + if t.test(template) && b.test(base) && a.test(addition) { + // SmithingTransformRecipe: transmute the base keeping its components. + return Some(base.transmute(result, 1)); + } + } + Smithing::Trim { template: t, base: b, addition: a, pattern } => { + if t.test(template) && b.test(base) && a.test(addition) { + let material = e.props(&addition.item)?.trim_material.clone()?; + let trim = (Arc::from(material.as_str()), Arc::from(pattern.as_str())); + if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) { + return None; + } + let mut out = ItemStack { count: 1, ..base.clone() }; + out.data_mut().trim = Some(trim); + return Some(out); + } + } + } + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::enchant::tests::{sample, sample_items}; + + fn sword(ench: &[(&str, u32)]) -> ItemStack { + let mut s = ItemStack::new("minecraft:diamond_sword", 1); + for (id, l) in ench { + s.enchant(id, *l); + } + s + } + fn book(ench: &[(&str, u32)]) -> ItemStack { + let mut s = ItemStack::new("minecraft:enchanted_book", 1); + for (id, l) in ench { + s.enchant(id, *l); + } + s + } + + #[test] + fn bookshelf_ring_has_32_positions() { + let o = bookshelf_offsets(); + assert_eq!(o.len(), 32); + assert!(o.contains(&[-2, 0, -2]) && o.contains(&[2, 1, 0]) && !o.contains(&[1, 0, 1])); + } + + #[test] + fn enchant_offers_are_deterministic_per_seed() { + let e = sample(); + let items = sample_items(); + let s = ItemStack::new("minecraft:diamond_sword", 1); + let a = enchant_offers(&e, &items, 1234, 15, Some(&s)); + let b = enchant_offers(&e, &items, 1234, 15, Some(&s)); + assert_eq!(a, b); + assert!(a.costs[2] >= 30 && a.costs[2] <= 30, "{a:?}"); + assert!(a.costs[0] >= 1 && a.costs[0] <= a.costs[2]); + // The clue is the first offer's random pick from the same list. + for slot in 0..3 { + let list = enchantment_list(&e, &items, 1234, slot, a.costs[slot], "minecraft:diamond_sword"); + let clue = a.clues[slot].clone().unwrap(); + assert!(list.contains(&clue)); + let applied = apply_enchantment(&e, &items, 1234, slot, a.costs[slot], &s).unwrap(); + assert_eq!(applied.enchantments(), &list[..]); + } + // Already enchanted items are not enchantable. + assert_eq!(enchant_offers(&e, &items, 1234, 15, Some(&sword(&[("minecraft:sharpness", 1)]))).costs, [0, 0, 0]); + let books = apply_enchantment(&e, &items, 99, 2, 30, &ItemStack::new("minecraft:book", 1)).unwrap(); + assert_eq!(&*books.item, "minecraft:enchanted_book"); + assert!(!books.stored_enchantments().is_empty()); + } + + #[test] + fn anvil_combines_and_charges_like_vanilla() { + let e = sample(); + let items = sample_items(); + // Sharpness II + Sharpness II book = Sharpness III; book fee 1/2 -> max(1, 0) = 1 per level. + let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 2)])), Some(&book(&[("minecraft:sharpness", 2)])), None, "Diamond Sword", false); + let out = r.result.unwrap(); + assert_eq!(out.enchantment_level("minecraft:sharpness"), 3); + assert_eq!(r.cost, 3); + assert_eq!(out.repair_cost(), 1); + // Incompatible only: no result. + let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 1)])), Some(&book(&[("minecraft:smite", 1)])), None, "Diamond Sword", false); + assert!(r.result.is_none()); + // Max level clamps: V + V stays V. + let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 5)])), Some(&book(&[("minecraft:sharpness", 5)])), None, "x", false); + assert_eq!(r.result.unwrap().enchantment_level("minecraft:sharpness"), 5); + assert_eq!(r.cost, 5); + } + + #[test] + fn anvil_rename_and_prior_work() { + let e = sample(); + let items = sample_items(); + let mut s = sword(&[]); + s.data_mut().repair_cost = 7; + let r = anvil_result(&e, &items, Some(&s), None, Some("Excalibur"), "Diamond Sword", false); + assert_eq!(r.cost, 8); + assert!(r.only_renaming); + let out = r.result.unwrap(); + assert_eq!(out.custom_name(), Some("Excalibur")); + // Renaming alone does not raise the penalty. + assert_eq!(out.repair_cost(), 7); + // Same name: nothing to do. + assert!(anvil_result(&e, &items, Some(&s), None, Some("Diamond Sword"), "Diamond Sword", false).result.is_none()); + // Too expensive at 40+ unless creative; rename-only caps at 39. + s.data_mut().repair_cost = 63; + let r = anvil_result(&e, &items, Some(&s), None, Some("A"), "Diamond Sword", false); + assert_eq!(r.cost, 39); + assert!(r.result.is_some()); + let r = anvil_result(&e, &items, Some(&s), Some(&book(&[("minecraft:unbreaking", 1)])), None, "Diamond Sword", false); + assert!(r.cost >= 40 && r.result.is_none()); + assert!(anvil_result(&e, &items, Some(&s), Some(&book(&[("minecraft:unbreaking", 1)])), None, "Diamond Sword", true).result.is_some()); + assert_eq!(increased_repair_cost(0), 1); + assert_eq!(increased_repair_cost(3), 7); + } + + #[test] + fn grindstone_strips_non_curses() { + let e = sample(); + let items = sample_items(); + let s = sword(&[("minecraft:sharpness", 3)]); + let out = grindstone_result(&e, &items, Some(&s), None).unwrap(); + assert!(out.enchantments().is_empty()); + assert_eq!(out.repair_cost(), 0); + assert!(out.extra.is_none()); + let b = grindstone_result(&e, &items, None, Some(&book(&[("minecraft:mending", 1)]))).unwrap(); + assert_eq!(&*b.item, "minecraft:book"); + assert!(grindstone_result(&e, &items, Some(&sword(&[])), None).is_none()); + let mut r = LegacyRandom::new(5); + // min cost of Sharpness III = 23; ceil(23/2)=12 -> 12..23. + let xp = grindstone_experience(&e, &mut r, Some(&s), None); + assert!((12..24).contains(&xp)); + } +}