//! Items from vanilla's default-component reports, block<->item mapping, //! tool mining rules and block loot tables (`LootTable`/`LootPool` semantics //! for the condition, entry and modifier types used by block drops). use crate::{Result, blocks::BlockFacts}; use horizon_core::random::RandomSource; use horizon_world::registry::{BlockRegistry, BlockStateId}; use serde_json::Value; use std::{ collections::{BTreeMap, HashMap, HashSet}, fs, path::Path, sync::Arc, }; /// A fire starter's use sound: `SoundEvents.FIRECHARGE_USE` or /// `FLINTANDSTEEL_USE`. pub fn fire_starter_sound(fire_charge: bool) -> &'static str { if fire_charge { "minecraft:item.firecharge.use" } else { "minecraft:item.flintandsteel.use" } } /// The pitch of a fire starter's use sound, from the level's random: /// `FlintAndSteelItem.useOn`'s `nextFloat() * 0.4 + 0.8`, or /// `FireChargeItem.playSound`'s `(nextFloat() - nextFloat()) * 0.2 + 1.0`. pub fn fire_starter_pitch(fire_charge: bool, random: &mut impl RandomSource) -> f32 { if fire_charge { (random.next_float() - random.next_float()) * 0.2 + 1.0 } else { random.next_float() * 0.4 + 0.8 } } #[derive(Clone, Debug)] pub struct ToolRule { pub blocks: Vec, pub speed: Option, pub correct: Option, } #[derive(Clone, Debug)] pub struct ItemInfo { pub id: Arc, pub max_stack: u32, pub max_damage: u32, pub block: Option, pub tool: Vec, pub tool_default_speed: f32, pub food: Option<(u32, f32)>, pub model: String, /// Main-hand `attack_damage` / `attack_speed` modifier amounts. pub attack_damage: f32, pub attack_speed: f32, /// `cooking_fuel`: burn-time and speed-multiplier provider references. pub fuel: Option<(Value, Value)>, /// `brewing_fuel`: uses and speed-multiplier provider references. pub brewing_fuel: Option<(Value, Value)>, /// `compostable.layers`: the layers provider (`ComposterBlock.addLayer`). pub compostable: Option, /// Item left behind after crafting/fuel use (e.g. bucket). pub remainder: Option, /// `equippable.slot` (head, chest, legs, feet, ...). pub equip_slot: Option, /// `equippable.asset_id`: the equipment asset drawn when worn. pub equip_asset: Option, /// All `attribute_modifiers`: (attribute, id, amount, operation, slot group). pub modifiers: Vec<(String, String, f64, String, String)>, /// `blocks_attacks` (shields). pub blocks_attacks: Option, /// `weapon.disable_blocking_for_seconds` (axes). pub disable_blocking_seconds: f32, /// `use_effects.speed_multiplier` (UseEffects.DEFAULT: 0.2). pub use_speed: f32, /// `glider` (elytra). pub glider: bool, /// `equippable.swappable` and `equip_sound`. pub swappable: bool, /// `equippable.dispensable` (dispensers may put it on an entity). pub equip_dispensable: bool, /// `equippable.allowed_entities` resolved to entity type ids; None allows all. pub equip_allowed: Option>, pub equip_sound: Option, /// `jukebox_playable`: the jukebox song it plays. pub jukebox_song: Option, /// `crafting_remainder`: what stays in the grid when the item is used in a recipe. pub crafting_remainder: Option, /// `dye`: the dye colour name (dyes, and anything else with the component). pub dye: Option, /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. pub block_transformer: Option, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [ ("minecraft:water_bucket", "minecraft:bucket"), ("minecraft:lava_bucket", "minecraft:bucket"), ("minecraft:milk_bucket", "minecraft:bucket"), ("minecraft:dragon_breath", "minecraft:glass_bottle"), ("minecraft:honey_bottle", "minecraft:glass_bottle"), ]; /// A reduction of `blocks_attacks.damage_reductions`. #[derive(Clone, Debug)] pub struct BlockReduction { pub horizontal_angle: f32, /// Damage type ids or `#tags`; None blocks every type. pub types: Option>, pub base: f32, pub factor: f32, } /// The `blocks_attacks` component. #[derive(Clone, Debug)] pub struct BlocksAttacks { pub delay_seconds: f32, pub disable_scale: f32, pub reductions: Vec, /// item_damage: (threshold, base, factor) pub item_damage: (f32, f32, f32), pub bypassed_by: Option, pub block_sound: Option, pub disabled_sound: Option, } impl BlocksAttacks { fn parse(v: &Value) -> Option { if !v.is_object() { return None; } let f = |v: &Value, d: f64| v.as_f64().unwrap_or(d) as f32; let text = |v: &Value| v.as_str().map(str::to_owned); let reductions = match v["damage_reductions"].as_array() { Some(list) => list .iter() .map(|r| BlockReduction { horizontal_angle: f(&r["horizontal_blocking_angle"], 90.0), types: match &r["type"] { Value::String(s) => Some(vec![s.clone()]), Value::Array(a) => Some( a.iter() .filter_map(|t| t.as_str().map(str::to_owned)) .collect(), ), _ => None, }, base: f(&r["base"], 0.0), factor: f(&r["factor"], 0.0), }) .collect(), // BlocksAttacks.CODEC default: block everything within 90 degrees. None => vec![BlockReduction { horizontal_angle: 90.0, types: None, base: 0.0, factor: 1.0, }], }; let d = &v["item_damage"]; Some(Self { delay_seconds: f(&v["block_delay_seconds"], 0.0), disable_scale: f(&v["disable_cooldown_scale"], 1.0), reductions, item_damage: if d.is_object() { ( f(&d["threshold"], 1.0), f(&d["base"], 0.0), f(&d["factor"], 1.0), ) } else { (1.0, 0.0, 1.0) }, bypassed_by: text(&v["bypassed_by"]), block_sound: text(&v["block_sound"]), disabled_sound: text(&v["disabled_sound"]), }) } } #[derive(Clone, Debug, PartialEq)] 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>, } /// `order`'s items in the registry's order (`command-registries.json`'s /// `items`, exported from the game); `order` itself when that is missing. fn registry_order(root: &Path, order: &[Arc]) -> Vec> { let listed: Vec = fs::read(root.join("command-registries.json")) .ok() .and_then(|b| serde_json::from_slice::(&b).ok()) .and_then(|v| serde_json::from_value(v["items"].clone()).ok()) .unwrap_or_default(); if listed.is_empty() { return order.to_vec(); } let known: HashSet<&str> = order.iter().map(|i| &**i).collect(); listed .iter() .filter(|i| known.contains(i.as_str())) .map(|i| Arc::from(i.as_str())) .collect() } /// Item ids standing for a loot table's `minecraft:dynamic` entries. const DYNAMIC: &str = "#dynamic:"; pub struct Items { pub items: HashMap, ItemInfo>, pub order: Vec>, /// The same items in item registry (network id) order, as vanilla lists /// them; sorted by name when the registry export is missing. pub registry_order: Vec>, /// Block tag name (without '#') -> member block names. pub block_tags: HashMap>, pub item_tags: HashMap>, /// Item tags in vanilla's order (`TagLoader`: file order, nested tags in /// place, first occurrence kept), the order `TagSlotDisplay` resolves. pub item_tag_order: HashMap>, loot: HashMap, /// The `jukebox_song` registry. pub songs: HashMap, } /// A `JukeboxSong`. #[derive(Clone, Debug)] pub struct Song { pub sound: String, pub length_ticks: i64, pub comparator: i32, pub description: Value, } impl Song { /// `hasFinished`: the length plus one second. pub fn finished(&self, ticks: i64) -> bool { ticks >= self.length_ticks + 20 } } fn load_songs(root: &Path) -> HashMap { let mut songs = HashMap::new(); let Ok(dir) = fs::read_dir(root.join("data/minecraft/jukebox_song")) else { return songs; }; for entry in dir.flatten() { let path = entry.path(); let (Some(stem), Ok(bytes)) = (path.file_stem().and_then(|s| s.to_str()), fs::read(&path)) else { continue; }; let Ok(v) = serde_json::from_slice::(&bytes) else { continue; }; let sound = match &v["sound_event"] { Value::String(s) => s.clone(), other => other["sound_id"].as_str().unwrap_or("").to_owned(), }; songs.insert( format!("minecraft:{stem}"), Song { sound, length_ticks: (v["length_in_seconds"].as_f64().unwrap_or(0.0) as f32 * 20.0).ceil() as i64, comparator: v["comparator_output"].as_i64().unwrap_or(0) as i32, description: v["description"].clone(), }, ); } songs } pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>> { Ok(load_tag_lists(root, kind)? .into_iter() .map(|(k, v)| (k, v.into_iter().collect())) .collect()) } /// Every tag's contents in `TagLoader.tryBuildTag` order (a `LinkedHashSet`). pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> 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<()> { for entry in fs::read_dir(dir)?.flatten() { let p = entry.path(); if p.is_dir() { walk(&p, base, raw)?; } else if p.extension().is_some_and(|e| e == "json") { let name = format!( "minecraft:{}", p.strip_prefix(base)? .with_extension("") .to_string_lossy() .replace('\\', "/") ); let v: Value = serde_json::from_slice(&fs::read(&p)?)?; 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(); raw.insert(name, values); } } Ok(()) } if dir.exists() { walk(&dir, &dir, &mut raw)?; } fn resolve(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { if depth > 32 { return; } for v in raw.get(name).into_iter().flatten() { if let Some(tag) = v.strip_prefix('#') { resolve(tag, raw, out, depth + 1); } else if !out.contains(v) { out.push(v.clone()); } } } Ok(raw .keys() .map(|k| { let mut list = Vec::new(); resolve(k, &raw, &mut list, 0); (k.clone(), list) }) .collect()) } /// An entity type id or `#tag` as the set of entity type ids it names. fn entity_spec(tags: &HashMap>, spec: &str) -> HashSet { match spec.strip_prefix('#') { Some(tag) => tags.get(tag).cloned().unwrap_or_default(), None => HashSet::from([spec.to_owned()]), } } impl Items { pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); for (i, s) in facts.states.iter().enumerate() { let default = registry.default_state(&s.name); if default == Some(BlockStateId(i as u32)) && &*s.item != "minecraft:air" { block_for_item .entry(&s.item) .or_insert(BlockStateId(i as u32)); } } Self::load_with(root, &block_for_item) } /// Every item's default components and the tags, without the block <-> /// item mapping (for headless tools that never place blocks). pub fn catalog(root: &Path) -> Result { Self::load_with(root, &HashMap::new()) } fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result { let raw: BTreeMap = serde_json::from_slice(&fs::read(root.join("items.json"))?)?; let entity_tags = load_tags(root, "entity_type")?; let mut items = HashMap::new(); let mut order = Vec::new(); for (name, c) in &raw { let id: Arc = Arc::from(name.as_str()); let tool = c["minecraft:tool"]["rules"] .as_array() .into_iter() .flatten() .map(|r| ToolRule { blocks: match &r["blocks"] { Value::String(s) => vec![s.clone()], Value::Array(a) => a .iter() .filter_map(|v| v.as_str().map(str::to_owned)) .collect(), _ => vec![], }, speed: r["speed"].as_f64().map(|v| v as f32), correct: r["correct_for_drops"].as_bool(), }) .collect(); let modifier = |kind: &str| -> f32 { c["minecraft:attribute_modifiers"] .as_array() .into_iter() .flatten() .filter(|m| { m["type"].as_str() == Some(kind) && m["operation"].as_str() == Some("add_value") }) .filter_map(|m| m["amount"].as_f64()) .sum::() as f32 }; let food = c.get("minecraft:food").map(|f| { ( f["nutrition"].as_u64().unwrap_or(0) as u32, f["saturation"].as_f64().unwrap_or(0.0) as f32, ) }); items.insert( id.clone(), ItemInfo { id: id.clone(), max_stack: c["minecraft:max_stack_size"].as_u64().unwrap_or(64) as u32, max_damage: c["minecraft:max_damage"].as_u64().unwrap_or(0) as u32, block: block_for_item.get(name.as_str()).copied(), tool, tool_default_speed: c["minecraft:tool"]["default_mining_speed"] .as_f64() .unwrap_or(1.0) as f32, food, model: c["minecraft:item_model"] .as_str() .unwrap_or(name) .to_owned(), glider: c["minecraft:glider"].is_object(), swappable: c["minecraft:equippable"]["swappable"] .as_bool() .unwrap_or(true), equip_dispensable: c["minecraft:equippable"]["dispensable"] .as_bool() .unwrap_or(true), equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] { Value::String(spec) => Some(entity_spec(&entity_tags, spec)), Value::Array(list) => Some( list.iter() .filter_map(Value::as_str) .flat_map(|spec| entity_spec(&entity_tags, spec)) .collect(), ), _ => None, }, equip_sound: c["minecraft:equippable"]["equip_sound"] .as_str() .map(str::to_owned), jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) .map(|(_, rest)| (*rest).to_owned()), use_speed: c["minecraft:use_effects"]["speed_multiplier"] .as_f64() .unwrap_or(0.2) as f32, blocks_attacks: BlocksAttacks::parse(&c["minecraft:blocks_attacks"]), disable_blocking_seconds: c["minecraft:weapon"]["disable_blocking_for_seconds"] .as_f64() .unwrap_or(0.0) as f32, equip_asset: c["minecraft:equippable"]["asset_id"] .as_str() .map(str::to_owned), equip_slot: c["minecraft:equippable"]["slot"] .as_str() .map(str::to_owned), modifiers: c["minecraft:attribute_modifiers"] .as_array() .into_iter() .flatten() .filter_map(|m| { Some(( m["type"].as_str()?.to_owned(), m["id"].as_str()?.to_owned(), m["amount"].as_f64()?, m["operation"].as_str().unwrap_or("add_value").to_owned(), m["slot"].as_str().unwrap_or("any").to_owned(), )) }) .collect(), fuel: c .get("minecraft:cooking_fuel") .map(|f| (f["burn_time"].clone(), f["speed_multiplier"].clone())), brewing_fuel: c .get("minecraft:brewing_fuel") .map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())), compostable: c.get("minecraft:compostable").map(|f| f["layers"].clone()), remainder: c["minecraft:use_remainder"]["id"] .as_str() .or(c["minecraft:crafting_remainder"]["id"].as_str()) .or(c["minecraft:crafting_remainder"].as_str()) .map(str::to_owned), attack_damage: modifier("minecraft:attack_damage"), attack_speed: modifier("minecraft:attack_speed"), }, ); order.push(id); } let mut loot = HashMap::new(); // Every loot table, keyed by its id (blocks/stone, entities/sheep/white, // gameplay/chicken_lay, shearing/sheep/red...). fn walk_loot(dir: &Path, base: &Path, loot: &mut HashMap) -> Result<()> { for entry in fs::read_dir(dir)?.flatten() { let p = entry.path(); if p.is_dir() { walk_loot(&p, base, loot)?; } else if p.extension().is_some_and(|e| e == "json") { let id = p .strip_prefix(base)? .with_extension("") .to_string_lossy() .replace('\\', "/"); loot.insert( format!("minecraft:{id}"), serde_json::from_slice(&fs::read(&p)?)?, ); } } Ok(()) } let loot_root = root.join("data/minecraft/loot_table"); walk_loot(&loot_root, &loot_root, &mut loot)?; let registry_order = registry_order(root, &order); Ok(Self { items, order, registry_order, block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, item_tag_order: load_tag_lists(root, "item")?, loot, songs: load_songs(root), }) } pub fn get(&self, id: &str) -> Option<&ItemInfo> { self.items.get(id) } /// Only the block and item tags, for tools that need tag membership. pub fn tags_only(root: &Path) -> Result { Ok(Self { items: HashMap::new(), order: Vec::new(), registry_order: Vec::new(), block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, item_tag_order: load_tag_lists(root, "item")?, loot: HashMap::new(), songs: HashMap::new(), }) } /// 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(), registry_order: Vec::new(), block_tags: HashMap::new(), item_tag_order: item_tags .iter() .map(|(k, v)| (k.clone(), v.iter().cloned().collect())) .collect(), item_tags, loot: HashMap::new(), songs: 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)), None => spec == block, } } /// `Tool.getMiningSpeed` for the held item (1.0 without a tool component). pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 { let Some(info) = held.and_then(|s| self.get(&s.item)) else { return 1.0; }; for rule in &info.tool { if let Some(speed) = rule.speed && rule.blocks.iter().any(|b| self.block_matches(b, block)) { return speed; } } if info.tool.is_empty() { 1.0 } else { info.tool_default_speed } } /// `Tool.isCorrectForDrops`. pub fn correct_for_drops(&self, held: Option<&ItemStack>, block: &str) -> bool { let Some(info) = held.and_then(|s| self.get(&s.item)) else { return false; }; for rule in &info.tool { if let Some(correct) = rule.correct && rule.blocks.iter().any(|b| self.block_matches(b, block)) { return correct; } } false } /// Whether a loot table (`minecraft:blocks/stone`, ...) exists. pub fn has_loot_table(&self, id: &str) -> bool { self.loot.contains_key(id) } /// `LootTable.getRandomItems` of an inline table. pub fn inline_loot_table( &self, table: &Value, random: &mut R, ) -> Vec { let empty = BTreeMap::new(); let ctx = LootContext { items: self, block: "", properties: &empty, held: None, killed_by_player: false, }; ctx.evaluate(table, random) } /// The server random sequence the block's loot table draws from. pub fn block_loot_sequence( &self, registry: &BlockRegistry, state: BlockStateId, ) -> Option { let block = registry.state(state)?; let name = block.name.trim_start_matches("minecraft:"); let standing = name.replacen("_wall_", "_", 1); let standing = standing.strip_prefix("wall_").unwrap_or(&standing); let standing = standing.replacen("wall_", "", 1); self.loot_sequence(&format!("minecraft:blocks/{name}")) .or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}"))) } /// Evaluate the block's loot table for a player break without explosions. pub fn block_drops( &self, registry: &BlockRegistry, state: BlockStateId, held: Option<&ItemStack>, random: &mut R, ) -> Vec { self.block_drops_in(registry, state, held, random, None) } /// `block_drops` drawing from the table's random sequence when it has one /// (`sequences`: the world's sequences and seed), as BlockState.getDrops. pub fn block_drops_in( &self, registry: &BlockRegistry, state: BlockStateId, held: Option<&ItemStack>, random: &mut R, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { self.block_drops_full(registry, state, held, &[], random, sequences) } /// `block_drops` with the block entity's dynamic drops (`LootParams.withDynamicDrop`: /// a decorated pot's sherds) in place of the `minecraft:dynamic` entries. pub fn block_drops_with( &self, registry: &BlockRegistry, state: BlockStateId, held: Option<&ItemStack>, dynamic: &[ItemStack], random: &mut impl RandomSource, ) -> Vec { self.block_drops_full(registry, state, held, dynamic, random, None) } /// `block_drops_in` with dynamic drops. pub fn block_drops_full( &self, registry: &BlockRegistry, state: BlockStateId, held: Option<&ItemStack>, dynamic: &[ItemStack], random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { let drops = self.block_drops_raw(registry, state, held, random, sequences); if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { return drops; } drops .into_iter() .flat_map(|d| { if d.item.starts_with(DYNAMIC) { dynamic.to_vec() } else { vec![d] } }) .collect() } fn block_drops_raw( &self, registry: &BlockRegistry, state: BlockStateId, held: Option<&ItemStack>, random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; }; let name = block.name.trim_start_matches("minecraft:"); // `Blocks.wallVariant`: wall signs, banners, heads, fans and torches // reuse the standing block's loot table. let standing = name.replacen("_wall_", "_", 1); let standing = standing.strip_prefix("wall_").unwrap_or(&standing); let standing = standing.replacen("wall_", "", 1); let table = self .loot .get(&format!("minecraft:blocks/{name}")) .or_else(|| self.loot.get(&format!("minecraft:blocks/{standing}"))); let Some(table) = table else { return vec![]; }; // LootTable.getRandomItems draws from the table's random sequence. if let (Some(seq), Some(sequences)) = ( table.get("random_sequence").and_then(Value::as_str), sequences, ) { let random = sequences.0.get(seq, sequences.1); let ctx = LootContext { items: self, block: &block.name, properties: &block.properties, held, killed_by_player: false, }; return ctx.evaluate(table, random); } let ctx = LootContext { items: self, block: &block.name, properties: &block.properties, held, killed_by_player: false, }; ctx.evaluate(table, random) } /// Evaluate an entity's loot table (`minecraft:entities/`). /// Evaluate any loot table by id (e.g. `minecraft:gameplay/chicken_lay`). pub fn loot_table( &self, id: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut R, ) -> Vec { let Some(table) = self.loot.get(id) else { return vec![]; }; let empty = BTreeMap::new(); let ctx = LootContext { items: self, block: "", properties: &empty, held, killed_by_player, }; ctx.evaluate(table, random) } /// The server random sequence a loot table draws from (`random_sequence`): /// vanilla's `LootContext.Builder.create` uses it instead of the level random. pub fn loot_sequence(&self, id: &str) -> Option { self.loot.get(id)?["random_sequence"] .as_str() .map(str::to_owned) } /// `loot_table` drawing from any random (a random sequence). pub fn loot_table_from( &self, id: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut impl RandomSource, ) -> Vec { let Some(table) = self.loot.get(id) else { return vec![]; }; let empty = BTreeMap::new(); let ctx = LootContext { items: self, block: "", properties: &empty, held, killed_by_player, }; ctx.evaluate(table, random) } pub fn entity_drops( &self, entity: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut R, ) -> Vec { let name = entity.trim_start_matches("minecraft:"); let Some(table) = self.loot.get(&format!("minecraft:entities/{name}")) else { return vec![]; }; let empty = BTreeMap::new(); let ctx = LootContext { items: self, block: "", properties: &empty, held, killed_by_player, }; ctx.evaluate(table, random) } } impl LootContext<'_> { fn evaluate(&self, table: &Value, random: &mut R) -> Vec { let ctx = self; let mut out = Vec::new(); for pool in table["pools"].as_array().into_iter().flatten() { if !ctx.conditions(pool, random) { continue; } // LootPool: rolls.getInt (Mth.randomBetweenInclusive for uniform rolls). let rolls = ctx.int_number(&pool["rolls"], random).max(0) as u32; for _ in 0..rolls { let mut produced = Vec::new(); ctx.choose( pool["entries"].as_array().map_or(&[][..], Vec::as_slice), random, &mut produced, ); for mut stack in produced { ctx.modifiers(&pool["modifier"], &mut stack, random); ctx.modifiers(&table["modifier"], &mut stack, random); if stack.count > 0 { out.push(stack); } } } } out } } struct LootContext<'a> { items: &'a Items, block: &'a str, properties: &'a BTreeMap, held: Option<&'a ItemStack>, killed_by_player: bool, } impl LootContext<'_> { /// Level of an enchantment on the tool / killer's weapon. fn enchantment_level(&self, id: &str) -> u32 { self.held.map_or(0, |h| h.enchantment_level(id)) } fn number(&self, v: &Value, random: &mut R) -> f32 { match v { Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, Value::Object(o) => match o .get("type") .and_then(Value::as_str) .unwrap_or("minecraft:uniform") { "minecraft:constant" => { o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32 } "minecraft:uniform" => { let min = self.number(o.get("min").unwrap_or(&Value::Null), random); let max = self.number(o.get("max").unwrap_or(&Value::Null), random); // UniformGenerator.getFloat / getInt (Mth.nextInt) differ; use int for counts. if max <= min { min } else { min + random.next_float() * (max - min) } } "minecraft:binomial" => { let n = self.number(o.get("n").unwrap_or(&Value::Null), random) as u32; let p = self.number(o.get("p").unwrap_or(&Value::Null), random); (0..n).filter(|_| random.next_float() < p).count() as f32 } _ => 1.0, }, _ => 1.0, } } fn int_number(&self, v: &Value, random: &mut R) -> i32 { if let Value::Object(o) = v && o.get("type") .and_then(Value::as_str) .unwrap_or("minecraft:uniform") == "minecraft:uniform" { let min = self.int_number(o.get("min").unwrap_or(&Value::Null), random); let max = self.int_number(o.get("max").unwrap_or(&Value::Null), random); return if max <= min { min } else { min + random.next_int_bound(max - min + 1).unwrap_or(0) }; } self.number(v, random).round() as i32 } fn condition(&self, c: &Value, random: &mut R) -> bool { let (kind, c) = match c { Value::String(s) => (s.as_str(), &Value::Null), Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c), _ => return true, }; match kind { "minecraft:survives_explosion" => true, "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), "minecraft:any_of" => c["terms"] .as_array() .into_iter() .flatten() .any(|t| self.condition(t, random)), "minecraft:all_of" => c["terms"] .as_array() .into_iter() .flatten() .all(|t| self.condition(t, random)), "minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random), "minecraft:table_bonus" => { // BonusLevelTableCondition: chances[min(level, len - 1)]. let level = self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) as usize; let chances = c["chances"].as_array().map_or(&[][..], Vec::as_slice); let chance = chances .get(level.min(chances.len().saturating_sub(1))) .and_then(Value::as_f64) .unwrap_or(0.0) as f32; random.next_float() < chance } "minecraft:match_block" | "minecraft:block_state_property" => { let blocks_ok = match &c["blocks"].as_str().or(c["block"].as_str()) { Some(spec) => self.items.block_matches(spec, self.block), None => true, }; blocks_ok && c["state"] .as_object() .into_iter() .flatten() .chain(c["properties"].as_object().into_iter().flatten()) .all(|(k, v)| { let have = self.properties.get(k).map(String::as_str); match v { Value::String(s) => have == Some(s.as_str()), Value::Object(r) => { let have: i64 = have.and_then(|h| h.parse().ok()).unwrap_or(0); r.get("min") .and_then(Value::as_i64) .is_none_or(|m| have >= m) && r.get("max") .and_then(Value::as_i64) .is_none_or(|m| have <= m) } _ => true, } }) } "minecraft:match_tool" => { let items = &c["predicate"]["items"]; let items_ok = match (self.held, items) { (_, Value::Null) => self.held.is_some(), (Some(h), Value::String(s)) => match s.strip_prefix('#') { Some(tag) => self .items .item_tags .get(tag) .is_some_and(|t| t.contains(&*h.item)), None => **s == *h.item, }, _ => false, }; // ItemPredicate "minecraft:enchantments": each entry needs a level in range. let enchants_ok = c["predicate"]["predicates"]["minecraft:enchantments"] .as_array() .into_iter() .flatten() .all(|e| { let level = self.enchantment_level(e["enchantments"].as_str().unwrap_or("")); let min = e["levels"]["min"].as_u64().unwrap_or(1) as u32; let max = e["levels"]["max"].as_u64().map_or(u32::MAX, |m| m as u32); level >= min.max(1) && level <= max }); items_ok && enchants_ok } "minecraft:killed_by_player" => self.killed_by_player, "minecraft:random_chance_with_enchanted_bonus" => { let level = if self.killed_by_player && self.block.is_empty() { self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) } else { 0 }; let chance = if level > 0 { crate::enchant::level_value(&c["enchanted_chance"], level) } else { c["unenchanted_chance"].as_f64().unwrap_or(0.0) as f32 }; random.next_float() < chance } // Entity flags, equipment and damage-source predicates: none hold // for an unenchanted player kill without fire or lightning. "minecraft:entity_properties" | "minecraft:damage_source_properties" => false, _ => true, } } fn conditions(&self, o: &Value, random: &mut R) -> bool { if let Some(c) = o.get("condition") && !self.condition(c, random) { return false; } o.get("conditions") .and_then(Value::as_array) .into_iter() .flatten() .all(|c| self.condition(c, random)) } /// Expand entries; returns whether an entry succeeded (for alternatives). fn expand( &self, e: &Value, random: &mut R, out: &mut Vec<(i32, ItemStack, Value)>, ) -> bool { if !self.conditions(e, random) { return false; } match e["type"].as_str().unwrap_or("") { "minecraft:item" => { out.push(( e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from(e["name"].as_str().unwrap_or("minecraft:air")), count: 1, damage: 0, extra: None, }, e["modifier"].clone(), )); true } "minecraft:alternatives" => { for child in e["children"].as_array().into_iter().flatten() { if self.expand(child, random, out) { return true; } } false } "minecraft:group" => { for child in e["children"].as_array().into_iter().flatten() { self.expand(child, random, out); } true } "minecraft:sequence" => { for child in e["children"].as_array().into_iter().flatten() { if !self.expand(child, random, out) { break; } } true } // DynamicLoot: what the block entity adds (a cracked decorated // pot's sherds), filled in by `block_drops_with`. "minecraft:dynamic" => { out.push(( e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from(format!("{DYNAMIC}{}", e["name"].as_str().unwrap_or(""))), count: 1, damage: 0, extra: None, }, Value::Null, )); true } "minecraft:empty" => { 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, } } fn choose( &self, entries: &[Value], random: &mut R, produced: &mut Vec, ) { let mut candidates = Vec::new(); for e in entries { self.expand(e, random, &mut candidates); } if candidates.is_empty() { return; } let pick = if candidates.len() == 1 { 0 } else { let total: i32 = candidates.iter().map(|c| c.0.max(0)).sum(); let mut r = random.next_int_bound(total.max(1)).unwrap_or(0); let mut chosen = 0; for (i, c) in candidates.iter().enumerate() { r -= c.0.max(0); if r < 0 { chosen = i; break; } } chosen }; let (_, mut stack, modifiers) = candidates.swap_remove(pick); self.modifiers(&modifiers, &mut stack, random); produced.push(stack); } fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut R) { let list: Vec<&Value> = match m { Value::Array(a) => a.iter().collect(), Value::Object(_) => vec![m], _ => return, }; for f in list { if !self.conditions(f, random) { continue; } match f["type"].as_str().or(f["function"].as_str()).unwrap_or("") { "minecraft:set_count" => { let n = self.int_number(&f["count"], random); let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { 0 }; stack.count = (base + n).max(0) as u32; } "minecraft:apply_bonus" => { let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")) as i32; let count = stack.count as i32; let params = &f["parameters"]; stack.count = match f["formula"].as_str().unwrap_or("") { "minecraft:ore_drops" if level > 0 => { let bonus = (random.next_int_bound(level + 2).unwrap_or(0) - 1).max(0); count * (bonus + 1) } "minecraft:uniform_bonus_count" => { let multiplier = params["bonusMultiplier"].as_i64().unwrap_or(1) as i32; count + random.next_int_bound(multiplier * level + 1).unwrap_or(0) } "minecraft:binomial_with_bonus_count" => { let (extra, p) = ( params["extra"].as_i64().unwrap_or(0) as i32, params["probability"].as_f64().unwrap_or(0.0) as f32, ); let mut n = count; for _ in 0..level + extra { if random.next_float() < p { n += 1; } } n } _ => count, } .max(0) as u32; } "minecraft:enchanted_count_increase" => { // Attacker's level x count, rounded (looting). let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")); if level > 0 && self.killed_by_player && self.block.is_empty() { let add = level as f32 * self.number(&f["count"], random); stack.count = (stack.count as i32 + add.round() as i32).max(0) as u32; if let Some(limit) = f["limit"].as_i64().filter(|l| *l > 0) { stack.count = stack.count.min(limit as u32); } } } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { stack.count = stack.count.max(min as u32); } if let Some(max) = limit["max"].as_i64() { stack.count = stack.count.min(max as u32); } } _ => {} } } } } #[cfg(test)] mod tests { use super::*; use horizon_core::random::LegacyRandom; use serde_json::json; fn ctx<'a>( items: &'a Items, held: Option<&'a ItemStack>, props: &'a BTreeMap, block: &'a str, ) -> LootContext<'a> { LootContext { items, block, properties: props, held, killed_by_player: block.is_empty(), } } #[test] fn fortune_silk_touch_and_looting() { let items = Items::for_tests(HashMap::new()); let props = BTreeMap::new(); let mut pick = ItemStack::new("minecraft:diamond_pickaxe", 1); pick.enchant("minecraft:fortune", 3); let ore = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:alternatives","children":[ {"type":"minecraft:item","condition":"minecraft:tool/can_silk_touch","name":"minecraft:diamond_ore"}, {"type":"minecraft:item","name":"minecraft:diamond","modifier":[{"type":"minecraft:apply_bonus","enchantment":"minecraft:fortune","formula":"minecraft:ore_drops"}]}]}]}]}); let mut random = LegacyRandom::new(7); let n = 20000; let total: u32 = (0..n) .map(|_| { ctx(&items, Some(&pick), &props, "minecraft:diamond_ore") .evaluate(&ore, &mut random) .iter() .map(|s| s.count) .sum::() }) .sum(); // Fortune III ore drops average (1 + 1 + 2 + 3 + 4) / 5 = 2.2 diamonds. let mean = f64::from(total) / f64::from(n); assert!((mean - 2.2).abs() < 0.05, "{mean}"); let mut silk = ItemStack::new("minecraft:diamond_pickaxe", 1); silk.enchant("minecraft:silk_touch", 1); let drops = ctx(&items, Some(&silk), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); assert_eq!(&*drops[0].item, "minecraft:diamond_ore"); let plain = ItemStack::new("minecraft:diamond_pickaxe", 1); let drops = ctx(&items, Some(&plain), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); assert_eq!((&*drops[0].item, drops[0].count), ("minecraft:diamond", 1)); // Looting III adds level x uniform(0, 1) on player kills. let flesh = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item","name":"minecraft:rotten_flesh","modifier":[ {"type":"minecraft:set_count","count":{"type":"minecraft:uniform","min":0.0,"max":2.0}}, {"type":"minecraft:enchanted_count_increase","count":{"type":"minecraft:uniform","min":0.0,"max":1.0},"enchantment":"minecraft:looting"}]}]}]}); let mut sword = ItemStack::new("minecraft:iron_sword", 1); sword.enchant("minecraft:looting", 3); let looted: u32 = (0..n) .map(|_| { ctx(&items, Some(&sword), &props, "") .evaluate(&flesh, &mut random) .iter() .map(|s| s.count) .sum::() }) .sum(); let base: u32 = (0..n) .map(|_| { ctx(&items, None, &props, "") .evaluate(&flesh, &mut random) .iter() .map(|s| s.count) .sum::() }) .sum(); assert!(f64::from(looted) / f64::from(n) > f64::from(base) / f64::from(n) + 1.0); // Table bonus uses the chance for the tool's level. let leaves = json!({"pools":[{"rolls":1,"conditions":[{"type":"minecraft:table_bonus","enchantment":"minecraft:fortune","chances":[0.0,0.0,0.0,1.0]}],"entries":[{"type":"minecraft:item","name":"minecraft:apple"}]}]}); assert_eq!( ctx(&items, Some(&pick), &props, "minecraft:oak_leaves") .evaluate(&leaves, &mut random) .len(), 1 ); assert!( ctx(&items, Some(&plain), &props, "minecraft:oak_leaves") .evaluate(&leaves, &mut random) .is_empty() ); } }