diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs new file mode 100644 index 000000000..0e6dede38 --- /dev/null +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -0,0 +1,266 @@ +//! Entity death drops for differential tests against vanilla +//! (tools/test_entity_death_loot_parity.py): reads the cases of +//! `VanillaEntityDeathLootOracle` and prints what `mobs::drops::die` drops. +//! +//! usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + mobs::{ + Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube, + }, + random_sequences::RandomSequences, +}; +use horizon_core::{geometry::Vec3, random::LegacyRandom}; +use horizon_world::loot::{LootDamage, LootData, LootEntity, LootStack}; +use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc}; + +/// `id[;enchantment:level...]`. +fn stack(spec: &str) -> LootStack { + let mut parts = spec.split(';'); + let mut s = LootStack { + item: parts.next().unwrap_or("minecraft:air").to_owned(), + count: 1, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: false, + ominous_amplifier: None, + }; + for e in parts { + let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + s.enchantments.push((name, level.parse().unwrap_or(1))); + } + s +} + +fn line(s: &LootStack) -> String { + let mut out = format!("drop {} {}", s.item, s.count); + if s.damage != 0 { + let _ = write!(out, " damage={}", s.damage); + } + for (e, l) in &s.enchantments { + let _ = write!(out, " ench={e}:{l}"); + } + if let Some(p) = &s.potion { + let _ = write!(out, " potion={p}"); + } + if let Some(a) = s.ominous_amplifier { + let _ = write!(out, " ominous={a}"); + } + out +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let types = MobTypes::load(root)?; + let loot = LootData::load(root)?; + let mut out = String::new(); + for raw in input.lines() { + if raw.trim().is_empty() || raw.starts_with('#') { + continue; + } + let mut c = BTreeMap::new(); + let mut name = ""; + for token in raw.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let _ = writeln!(out, "== {name}"); + let Some(kind) = types.types.get(c["type"]) else { + let _ = writeln!(out, "error unsupported {}", c["type"]); + continue; + }; + let kind = Arc::new(kind.clone()); + let world_seed: i64 = get("seed", "0").parse()?; + let kills: i64 = get("kills", "1").parse()?; + let rand: i64 = get("rand", "0").parse()?; + let mut sequences = RandomSequences::default(); + for k in 0..kills { + let _ = writeln!(out, "kill {k}"); + let mut m = Mob::new(1, kind.clone(), Vec3::new(0.5, 64.0, 0.5), 0.0); + // EntityType.create(LOAD) gives no equipment. + for slot in drops::SLOTS { + drops::clear_slot(&mut m, slot); + } + if get("baby", "0") == "1" && drops::can_be_baby(m.species()) { + m.extra.age = -24000; + } + if get("fire", "0") == "1" { + m.fire_ticks = 100; + } + // A cube made with EntityType.create(LOAD) was never sized. + if matches!(m.species(), Species::Slime | Species::MagmaCube) { + m.extra.size = 0; + } + if let Some(size) = c.get("size") { + let size: i32 = size.parse()?; + if m.species() == Species::SulfurCube { + sulfur_cube::set_size(&mut m, size, true); + } else { + cube::set_size(&mut m, size); + } + } + if let Some(color) = c.get("color") { + m.extra.color = DYE_NAMES.iter().position(|d| d == color).unwrap_or(0) as u8; + } + m.extra.sheared = get("sheared", "0") == "1"; + if get("leader", "0") == "1" { + raider::state_mut(&mut m).patrol_leader = true; + } + if get("captain", "0") == "1" { + m.extra.head = Some(Arc::from(raider::BANNER)); + } + let mut chances = [drops::DEFAULT_DROP_CHANCE; 8]; + for (i, slot) in drops::SLOTS.iter().enumerate() { + if let Some(spec) = c.get(slot) { + let s = stack(spec); + let item: Option> = Some(Arc::from(s.item.as_str())); + let index = match *slot { + "mainhand" => { + m.extra.main_hand = item; + Some(gear::MAIN) + } + "offhand" => { + m.extra.off_hand = item; + Some(gear::OFF) + } + "head" => { + m.extra.head = item; + Some(gear::HEAD) + } + "body" if drops::head_is_body(m.species()) => { + m.extra.head = item; + None + } + "saddle" => { + m.set_saddle(Some(horizon_client::items::ItemStack::new(&s.item, 1))); + None + } + "chest" => { + m.extra.chest = item; + Some(gear::CHEST) + } + "legs" => { + m.extra.legs = item; + Some(gear::LEGS) + } + "feet" => { + m.extra.feet = item; + Some(gear::FEET) + } + _ => None, + }; + if let Some(index) = index + && !s.enchantments.is_empty() + { + let levels = s + .enchantments + .iter() + .map(|(e, l)| (Arc::from(e.as_str()), *l as u32)) + .collect(); + gear::set(&mut m, index, levels); + } + } + if let Some(chance) = c.get(format!("chance_{slot}").as_str()) { + chances[i] = chance.parse()?; + } + } + m.extra.drop_chances = Some(Box::new(chances)); + m.random = LegacyRandom::new(rand + k); + // The killer, the last player to hurt the victim and the damage source. + let killer_id = get("killer", "none"); + let weapon = c.get("weapon").map(|w| stack(w)); + let armed = |kind: &str| { + let mut e = LootEntity::new(kind); + if let Some(w) = &weapon { + e.equipment.push(("mainhand".into(), w.clone())); + } + e + }; + let player = (killer_id == "player" || get("pkill", "0") == "1").then(|| { + if killer_id == "player" { + armed("minecraft:player") + } else { + LootEntity::new("minecraft:player") + } + }); + let killer = match killer_id.as_str() { + "player" => player.clone(), + "none" => None, + id => { + let mut e = armed(id); + e.frog_variant = c.get("frog").map(|f| f.to_string()); + e.powered = get("charged", "0") == "1"; + Some(e) + } + }; + let pkill = get("pkill", if killer_id == "player" { "1" } else { "0" }) == "1"; + let projectile = |kind: &str| LootEntity { + kind: kind.to_owned(), + ..LootEntity::default() + }; + let damage = |kind: &str, source: Option, direct: Option| LootDamage { + kind: kind.to_owned(), + source, + direct, + }; + let source = match get("source", "attack").as_str() { + "attack" => match &killer { + None => damage("minecraft:generic", None, None), + Some(k) if k.kind == "minecraft:player" => { + damage("minecraft:player_attack", Some(k.clone()), Some(k.clone())) + } + Some(k) => damage("minecraft:mob_attack", Some(k.clone()), Some(k.clone())), + }, + "arrow" => damage("minecraft:arrow", killer.clone(), Some(projectile("minecraft:arrow"))), + "fireball" => match &killer { + Some(k) => damage("minecraft:fireball", Some(k.clone()), Some(projectile("minecraft:fireball"))), + None => damage( + "minecraft:unattributed_fireball", + Some(projectile("minecraft:fireball")), + Some(projectile("minecraft:fireball")), + ), + }, + "explosion" => match &killer { + Some(k) => damage("minecraft:player_explosion", Some(k.clone()), Some(k.clone())), + None => damage("minecraft:explosion", None, None), + }, + "lightning" => damage("minecraft:lightning_bolt", None, None), + "fire" => damage("minecraft:on_fire", None, None), + _ => damage("minecraft:generic", None, None), + }; + let death = drops::Death { + loot: &loot, + damage: Some(source), + player: player.filter(|_| pkill), + luck: get("luck", "0").parse()?, + vehicle: c.get("vehicle").map(|v| LootEntity::new(v)), + mob_drops: true, + world_seed, + }; + let (items, _) = drops::die(&mut m, &death, &mut sequences); + for d in items { + let _ = match d { + drops::Drop::Item(s) => writeln!(out, "{}", line(&s)), + drops::Drop::Orb(v) => writeln!(out, "orb {v}"), + }; + } + } + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 26c1bf86f..afd148af7 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -739,13 +739,14 @@ impl Game<'_> { /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby - // takes the experience. + // takes the experience (before the loot is dropped). self.sculk_mob_died(m); let consumed = - self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |game| { + self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |_| { if by_player { - experience_reward(m, &mut game.world.random) + horizon_client::mobs::drops::base_experience(&mut dying).max(0) as u32 } else { 0 } @@ -760,103 +761,8 @@ impl Game<'_> { self.score_entity_removed(m.id); self.raider_died(m, by_player); self.villager_murdered(m, by_player); - let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; - if !m.is_baby() { - let mut drops = self.res.items.entity_drops( - &m.kind.id, - by_player, - held.as_ref(), - &mut self.world.random, - ); - if m.species() == Species::Sheep && !m.extra.sheared { - let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; - drops.extend(self.res.items.loot_table( - &format!("minecraft:entities/sheep/{color}"), - by_player, - held.as_ref(), - &mut self.world.random, - )); - } - for d in drops { - if d.count > 0 && &*d.item != "minecraft:air" { - self.spawn_item(d, pos, [0.0, 0.2, 0.0], 10); - } - } - // Saddles, horse armour and chests always drop. - let mut gear: Vec<&str> = Vec::new(); - if let Some(saddle) = m.saddle_item() { - self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10); - } - // WitherBoss.dropCustomDeathLoot. - if m.species() == Species::Wither { - gear.push("minecraft:nether_star"); - } - if species_drops_harness(m) - && let Some(h) = m.extra.head.as_deref() - { - gear.push(h); - } - if m.extra.chested && horizon_client::mobs::equine::is_equine(m.species()) { - gear.push("minecraft:chest"); - } - if horizon_client::mobs::equine::is_equine(m.species()) - && let Some(armor) = m.extra.head.as_deref() - { - gear.push(armor); - } - for item in gear { - self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10); - } - // AbstractChestedHorse.dropEquipment: the chest contents. - for stack in m.extra.items.clone().into_iter().flatten() { - self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10); - } - self.raider_death_loot(m, pos); - let worn = if horizon_client::mobs::equine::is_equine(m.species()) { - [None, None, None, None] - } else { - [ - m.extra.head.clone(), - m.extra.chest.clone(), - m.extra.legs.clone(), - m.extra.feet.clone(), - ] - }; - for (index, item) in std::iter::once(m.extra.main_hand.clone()) - .chain(worn) - .enumerate() - { - // Main hand, then head to feet (the enchantment slots). - let slot = if index == 0 { - horizon_client::mobs::gear::MAIN - } else { - horizon_client::mobs::gear::HEAD + index - 1 - }; - // Equipment drop chance 8.5% (+ player kill only). - // Vexes never drop their sword. - if let Some(item) = &item - && by_player - && &**item != horizon_client::mobs::raider::BANNER - && m.species() != Species::Vex - && self.world.random.next_float() < 0.085 - { - let mut stack = ItemStack::new(item, 1); - if let Some(g) = horizon_client::mobs::gear::gear(m) { - for (e, l) in &g.slots[slot] { - stack.enchant(e, *l); - } - } - self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10); - } - } - } - if by_player && !consumed { - let xp = experience_reward(m, &mut self.world.random); - if xp > 0 { - self.spawn_orbs(pos, xp); - } - } + self.drop_death_loot(&mut dying, by_player, consumed, pos); if m.species() == Species::SulfurCube { self.split_sulfur_cube(m); } @@ -881,6 +787,88 @@ impl Game<'_> { } } } + /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the + /// world's random sequence, equipment by drop chance, species extras and + /// the experience orbs, spawned in order. + fn drop_death_loot(&mut self, m: &mut Mob, by_player: bool, consumed: bool, pos: [f64; 3]) { + use horizon_client::mobs::{DamageKind, Who, drops}; + use horizon_world::loot::{LootDamage, LootEntity}; + let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) else { + return; + }; + let player = || { + let mut e = LootEntity::new("minecraft:player"); + if let Some(held) = self.held() { + e.equipment.push(("mainhand".into(), to_loot(held))); + } + e + }; + let damage = m.last_damage.map(|(d, _)| { + let source = match d.attacker { + Some(Who::Player) => Some(player()), + Some(Who::Mob(id)) => self + .mobs + .iter() + .find(|o| o.id == id) + .map(|o| drops::loot_entity(o, None)), + None => None, + }; + let direct = match d.kind { + DamageKind::Arrow => Some(LootEntity { + kind: "minecraft:arrow".into(), + ..LootEntity::default() + }), + DamageKind::Fireball => Some(LootEntity { + kind: "minecraft:fireball".into(), + ..LootEntity::default() + }), + _ => source.clone(), + }; + let player_source = matches!(d.attacker, Some(Who::Player)); + LootDamage { + kind: damage_type(d.kind, player_source).into(), + source, + direct, + } + }); + let vehicle = m + .extra + .mount + .and_then(|id| self.mobs.iter().find(|o| o.id == id)) + .map(|o| LootEntity::new(&o.kind.id)); + let death = drops::Death { + loot: &loot, + damage, + player: by_player.then(player), + luck: 0.0, + vehicle, + mob_drops: self.ui.rules.bool("mob_drops"), + world_seed: self.level.seed, + }; + let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences); + if skulls + && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) + && let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) + { + // Creeper.droppedSkulls: one head per charged explosion. + creeper.extra.charged = false; + } + let raider = horizon_client::mobs::raider::is_raider(m.species()); + for d in items { + match d { + drops::Drop::Item(stack) => { + let item = if raider && stack.item == horizon_client::mobs::raider::BANNER { + horizon_client::mobs::raider::ominous_banner() + } else { + from_loot(&stack) + }; + self.spawn_item(item, pos, [0.0, 0.2, 0.0], 10); + } + drops::Drop::Orb(value) if !consumed => self.spawn_orbs(pos, value as u32), + drops::Drop::Orb(_) => {} + } + } + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { @@ -2614,11 +2602,6 @@ impl Game<'_> { } } } -fn species_drops_harness(m: &Mob) -> bool { - // Body equipment set to drop when killed: a harness, nautilus armour, a - // sulfur cube's swallowed block. - horizon_client::mobs::species::body_slot(m.species()) -} fn eat_sound(s: Species) -> &'static str { match s { Species::Pig => "entity.pig.eat", @@ -2633,37 +2616,66 @@ fn eat_sound(s: Species) -> &'static str { } } /// Mob.getBaseExperienceReward -fn experience_reward(m: &Mob, random: &mut impl RandomSource) -> u32 { - use Species as S; - match m.species() { - S::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute | S::Breeze => 10, - S::Slime | S::MagmaCube => m.extra.size.max(1) as u32, - S::Endermite => 3, - S::Bat - | S::Squid - | S::GlowSquid - | S::Cod - | S::Salmon - | S::TropicalFish - | S::Pufferfish - | S::Dolphin => 1 + random.next_int_bound(3).unwrap_or(0) as u32, - S::IronGolem | S::SnowGolem | S::Villager | S::WanderingTrader => 0, - // SulfurCube.getBaseExperienceReward. - S::SulfurCube if m.is_baby() => 0, - S::SulfurCube => 1 + random.next_int_bound(2).unwrap_or(0) as u32, - // Animals in the monster category (Animal.getBaseExperienceReward). - S::CamelHusk | S::ZombieNautilus => 1 + random.next_int_bound(3).unwrap_or(0) as u32, - _ if m.hostile() => { - 5 + if m.extra.main_hand.is_some() { - 1 + random.next_int_bound(3).unwrap_or(0) as u32 - } else { - 0 - } - } - _ if m.is_baby() => 0, - _ => 1 + random.next_int_bound(3).unwrap_or(0) as u32, +/// The damage type id of a Horizon damage kind. +fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { + use horizon_client::mobs::DamageKind as K; + match kind { + K::PlayerAttack => "minecraft:player_attack", + K::MobAttack => "minecraft:mob_attack", + K::Arrow => "minecraft:arrow", + K::Thrown => "minecraft:thrown", + K::Fireball => "minecraft:fireball", + K::Explosion if player => "minecraft:player_explosion", + K::Explosion => "minecraft:explosion", + K::Fall => "minecraft:fall", + K::OnFire => "minecraft:on_fire", + K::InFire => "minecraft:in_fire", + K::Lava => "minecraft:lava", + K::Drown => "minecraft:drown", + K::Magic => "minecraft:magic", + K::Sting => "minecraft:sting", + K::Cactus => "minecraft:cactus", + K::Generic => "minecraft:generic", + K::InWall => "minecraft:in_wall", + K::Thorns => "minecraft:thorns", + K::SonicBoom => "minecraft:sonic_boom", } } +/// A Horizon item stack as a loot stack (id, count, damage, enchantments). +fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { + horizon_world::loot::LootStack { + item: stack.item.to_string(), + count: stack.count as i32, + damage: stack.damage as i32, + enchantments: stack + .enchantments() + .iter() + .map(|(e, l)| (e.to_string(), *l as i32)) + .collect(), + potion: None, + map: false, + ominous_amplifier: None, + } +} +/// A generated loot stack as a Horizon item stack. +fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = ItemStack { + item: Arc::from(stack.item.as_str()), + count: stack.count.max(1) as u32, + damage: stack.damage.max(0) as u32, + extra: None, + }; + for (id, level) in &stack.enchantments { + item.enchant(id, (*level).max(0) as u32); + } + if let Some(potion) = &stack.potion { + item = item.with_potion(potion); + } + if let Some(amplifier) = stack.ominous_amplifier.filter(|a| *a > 0) { + item.data_mut().ominous_amplifier = Some(amplifier as u8); + } + item +} /// Entity.push between overlapping mobs (LivingEntity.pushEntities). fn push_apart(mobs: &mut [Mob]) { let n = mobs.len(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 3e2fdad58..91c454ce8 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -921,21 +921,6 @@ impl Game<'_> { } /// A raider's ominous banner (drop chance 2.0: always dropped) and a /// patrol captain's ominous bottle (`entities/pillager`). - pub(super) fn raider_death_loot(&mut self, m: &horizon_client::mobs::Mob, pos: [f64; 3]) { - if !raider::is_raider(m.species()) { - return; - } - if m.extra.head.as_deref() == Some(raider::BANNER) { - self.spawn_item(raider::ominous_banner(), pos, [0.0, 0.2, 0.0], 10); - } - if m.species() == Species::Pillager && raider::is_captain(m) { - let amplifier = self.world.random.next_int_bound(5).unwrap_or(0) as u8; - let amplifier = (amplifier > 0).then_some(amplifier); - let mut bottle = horizon_client::items::ItemStack::new("minecraft:ominous_bottle", 1); - bottle.data_mut().ominous_amplifier = amplifier; - self.spawn_item(bottle, pos, [0.0, 0.2, 0.0], 10); - } - } /// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the /// bottle's amplifier, then the dispose sound; the bottle is used up. pub(super) fn drink_ominous_bottle( diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f46420cad..deda5984a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -18,6 +18,7 @@ pub mod control; pub mod creaking; pub mod cube; pub mod data; +pub mod drops; pub mod enderman; pub mod equine; pub mod farm; @@ -528,6 +529,9 @@ pub struct Extra { pub trap_time: i32, /// Enchantments on the equipment above. pub gear: Option>, + /// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set + /// explicitly; None uses the defaults of `drops::drop_chance`. + pub drop_chances: Option>, } #[derive(Clone, Debug)] pub struct Mob { diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs new file mode 100644 index 000000000..42010afd9 --- /dev/null +++ b/crates/horizon-client/src/mobs/drops.rs @@ -0,0 +1,530 @@ +//! What a dying mob leaves behind: `LivingEntity.die`'s drop step. The +//! killer's `killedEntity` hook (a charged creeper's head drop), then +//! `dropAllDeathLoot`: the entity loot table (drawn from the world's random +//! sequence), `Mob.dropCustomDeathLoot` (equipment by drop chance, with the +//! entity random), the species' extra drops and the experience orbs. +use super::{Mob, Species, equine, gear, raider, render::DYE_NAMES, species}; +use crate::random_sequences::RandomSequences; +use horizon_core::random::RandomSource; +use horizon_world::loot::{EntityLootParams, LootDamage, LootData, LootEntity, LootStack}; + +/// `DropChances.DEFAULT_EQUIPMENT_DROP_CHANCE`. +pub const DEFAULT_DROP_CHANCE: f32 = 0.085; +/// `EquipmentSlot.VALUES`. +pub use horizon_world::loot::EQUIPMENT_SLOTS as SLOTS; + +/// One thing a death leaves in the world, in spawn order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Drop { + Item(LootStack), + /// An experience orb of this value. + Orb(i32), +} + +/// How the mob died. +pub struct Death<'a> { + pub loot: &'a LootData, + /// The killing `DamageSource`. + pub damage: Option, + /// The player who last hurt the mob, when `lastHurtByPlayerMemoryTime > 0`. + pub player: Option, + /// That player's luck. + pub luck: f32, + /// The entity the mob rides. + pub vehicle: Option, + /// The `doMobLoot` game rule. + pub mob_drops: bool, + pub world_seed: i64, +} + +/// `instanceof Monster` (Monster.shouldDropLoot/shouldDropExperience). +pub fn is_monster(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Blaze + | S::Bogged + | S::Breeze + | S::CaveSpider + | S::Creaking + | S::Creeper + | S::Drowned + | S::ElderGuardian + | S::Enderman + | S::Endermite + | S::Evoker + | S::Giant + | S::Guardian + | S::Husk + | S::Illusioner + | S::Parched + | S::Piglin + | S::PiglinBrute + | S::Pillager + | S::Ravager + | S::Silverfish + | S::Skeleton + | S::Spider + | S::Stray + | S::Vex + | S::Vindicator + | S::Warden + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::Zombie + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// `Mob.xpReward` as the constructors set it. +fn xp_reward(m: &Mob) -> i32 { + use Species as S; + match m.species() { + S::Blaze | S::Breeze | S::Guardian | S::ElderGuardian | S::Evoker => 10, + S::Vex | S::Endermite => 3, + S::PiglinBrute | S::Ravager => 20, + S::Wither => 50, + S::Creaking => 0, + // Hoglin.setBaby. + S::Hoglin if m.is_baby() => 3, + S::Ghast | S::Hoglin | S::Phantom | S::Shulker => 5, + // Slime.setSize / MagmaCube.setSize (unsized cubes keep 0). + S::Slime | S::MagmaCube => m.extra.size.max(0), + s if is_monster(s) => 5, + _ => 0, + } +} +fn is_animal(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Armadillo + | S::Axolotl + | S::Bee + | S::Camel + | S::CamelHusk + | S::Cat + | S::Chicken + | S::Cow + | S::Donkey + | S::Fox + | S::Frog + | S::HappyGhast + | S::Goat + | S::Hoglin + | S::Horse + | S::Llama + | S::Mooshroom + | S::Mule + | S::Nautilus + | S::Ocelot + | S::Panda + | S::Parrot + | S::Pig + | S::PolarBear + | S::Rabbit + | S::Sheep + | S::SkeletonHorse + | S::Sniffer + | S::Strider + | S::TraderLlama + | S::Turtle + | S::Wolf + | S::ZombieHorse + | S::ZombieNautilus + ) +} +/// AgeableWaterCreature and WaterAnimal. +fn is_water_creature(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Dolphin + | S::GlowSquid + | S::Squid + | S::Cod + | S::Salmon + | S::Pufferfish + | S::TropicalFish + | S::Tadpole + ) +} +fn zombie_family(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin + ) +} +fn is_raider(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Pillager | S::Vindicator | S::Evoker | S::Illusioner | S::Witch | S::Ravager + ) +} +/// Whether `setBaby(true)` makes the species a baby (AgeableMob and the +/// zombies, minus the species that are never babies). +pub fn can_be_baby(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Armadillo + | S::Axolotl + | S::Bee + | S::Camel + | S::Cat + | S::Chicken + | S::Cow + | S::Dolphin + | S::Donkey + | S::Drowned + | S::Fox + | S::HappyGhast + | S::GlowSquid + | S::Goat + | S::Hoglin + | S::Horse + | S::Husk + | S::Llama + | S::Mooshroom + | S::Mule + | S::Nautilus + | S::Ocelot + | S::Panda + | S::Pig + | S::Piglin + | S::PolarBear + | S::Rabbit + | S::Sheep + | S::SkeletonHorse + | S::Sniffer + | S::Squid + | S::Strider + | S::SulfurCube + | S::TraderLlama + | S::Turtle + | S::Villager + | S::WanderingTrader + | S::Wolf + | S::Zoglin + | S::Zombie + | S::ZombieHorse + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// Whether the species keeps its body armour in `extra.head`. +pub fn head_is_body(s: Species) -> bool { + species::body_slot(s) || equine::is_equine(s) +} + +/// The item a mob has in an `EquipmentSlot` (by name), with its enchantments. +pub fn slot_item(m: &Mob, slot: &str) -> Option { + let body = head_is_body(m.species()); + let (item, index) = match slot { + "mainhand" => (m.extra.main_hand.as_deref(), Some(gear::MAIN)), + "offhand" => (m.extra.off_hand.as_deref(), Some(gear::OFF)), + "head" if !body => (m.extra.head.as_deref(), Some(gear::HEAD)), + "chest" => (m.extra.chest.as_deref(), Some(gear::CHEST)), + "legs" => (m.extra.legs.as_deref(), Some(gear::LEGS)), + "feet" => (m.extra.feet.as_deref(), Some(gear::FEET)), + "body" if body => (m.extra.head.as_deref(), None), + "saddle" => { + let saddle = m.saddle_item()?; + let mut stack = loot_stack(&saddle.item, 1); + stack.damage = saddle.damage as i32; + for (e, l) in saddle.enchantments() { + stack.enchantments.push((e.to_string(), *l as i32)); + } + return Some(stack); + } + _ => (None, None), + }; + let mut stack = loot_stack(item?, 1); + if let (Some(index), Some(g)) = (index, gear::gear(m)) { + for (e, l) in &g.slots[index] { + stack.enchantments.push((e.to_string(), *l as i32)); + } + } + Some(stack) +} +/// `setItemSlot(slot, EMPTY)`. +pub fn clear_slot(m: &mut Mob, slot: &str) { + let body = head_is_body(m.species()); + let index = match slot { + "mainhand" => { + m.extra.main_hand = None; + gear::MAIN + } + "offhand" => { + m.extra.off_hand = None; + gear::OFF + } + "head" if !body => { + m.extra.head = None; + gear::HEAD + } + "chest" => { + m.extra.chest = None; + gear::CHEST + } + "legs" => { + m.extra.legs = None; + gear::LEGS + } + "feet" => { + m.extra.feet = None; + gear::FEET + } + "body" if body => { + m.extra.head = None; + return; + } + "saddle" => { + m.set_saddle(None); + return; + } + _ => return, + }; + if m.extra.gear.is_some() { + gear::set(m, index, Vec::new()); + } +} +fn loot_stack(item: &str, count: i32) -> LootStack { + LootStack { + item: item.to_owned(), + count, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: false, + ominous_amplifier: None, + } +} +/// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the +/// game's spawn and equip paths give (saddles and body armour are put on by +/// `Equippable` and always drop; a captain's banner always drops; a vex +/// never drops its sword). +pub fn drop_chance(m: &Mob, slot: &str) -> f32 { + let index = SLOTS.iter().position(|s| *s == slot).unwrap_or(0); + if let Some(chances) = &m.extra.drop_chances { + return chances[index]; + } + match slot { + "saddle" | "body" => 2.0, + "head" if is_raider(m.species()) && m.extra.head.as_deref() == Some(raider::BANNER) => 2.0, + "mainhand" if m.species() == Species::Vex => 0.0, + _ => DEFAULT_DROP_CHANCE, + } +} +/// The facts loot predicates read about a mob. +pub fn loot_entity(m: &Mob, vehicle: Option) -> LootEntity { + use Species as S; + let s = m.species(); + let mut e = LootEntity::new(&m.kind.id); + e.on_fire = m.fire_ticks > 0 && !m.kind.flags.fire_immune; + e.baby = m.is_baby(); + e.vehicle = vehicle.map(Box::new); + if matches!(s, S::Slime | S::MagmaCube | S::SulfurCube) { + // An unsized cube has the synced default size 1. + e.cube_size = Some(m.extra.size.max(1)); + } + if s == S::Sheep { + e.sheep = Some(( + DYE_NAMES[m.extra.color as usize & 15].to_owned(), + m.extra.sheared, + )); + } + if is_raider(s) { + e.captain = Some(raider::is_captain(m)); + } + if s == S::Frog { + e.frog_variant = Some( + ["minecraft:temperate", "minecraft:warm", "minecraft:cold"] + [usize::from(m.extra.variant).min(2)] + .to_owned(), + ); + } + e.powered = s == S::Creeper && m.extra.charged; + e.equipment = SLOTS + .iter() + .filter_map(|slot| slot_item(m, slot).map(|i| (slot.to_string(), i))) + .collect(); + e +} +/// `ExperienceOrb.getExperienceValue`. +pub fn orb_value(amount: i32) -> i32 { + for v in [2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3] { + if amount >= v { + return v; + } + } + 1 +} + +/// `LivingEntity.die`'s drops for `m` (equipment it loses is removed from +/// it). Returns the drops in spawn order and whether a charged creeper +/// killer dropped a head (`Creeper.droppedSkulls`). +pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec, bool) { + let mut out = Vec::new(); + let this = loot_entity(m, d.vehicle.clone()); + let mut skulls = false; + // Creeper.killedEntity: a charged creeper's victim drops its head. + if let Some(source) = d.damage.as_ref().and_then(|x| x.source.as_ref()) + && source.kind == "minecraft:creeper" + && source.powered + && d.mob_drops + { + let params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: None, + luck: 0.0, + }; + let items = roll(d, "minecraft:charged_creeper/root", ¶ms, sequences); + skulls = items.iter().any(|i| !i.is_empty()); + out.extend(items.into_iter().filter(|i| !i.is_empty()).map(Drop::Item)); + } + let killed_by_player = d.player.is_some(); + let s = m.species(); + // Fox.dropAllDeathLoot: whatever it holds in its mouth comes out first. + if s == Species::Fox + && let Some(stack) = slot_item(m, "mainhand") + { + out.push(Drop::Item(stack)); + clear_slot(m, "mainhand"); + } + let drops_loot = d.mob_drops && (is_monster(s) || !m.is_baby()); + if drops_loot { + let table = format!("minecraft:entities/{}", m.kind.id.trim_start_matches("minecraft:")); + let params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: d.player.clone().filter(|_| killed_by_player), + luck: if killed_by_player { d.luck } else { 0.0 }, + }; + let items = roll(d, &table, ¶ms, sequences); + out.extend(items.into_iter().filter(|i| !i.is_empty()).map(Drop::Item)); + // Mob.dropCustomDeathLoot. + let damage_params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: None, + luck: 0.0, + }; + let living_attacker = d + .damage + .as_ref() + .and_then(|x| x.source.as_ref()) + .is_some_and(|a| a.living); + for slot in SLOTS { + let stack = slot_item(m, slot); + let mut chance = drop_chance(m, slot); + if chance == 0.0 { + continue; + } + let preserve = chance > 1.0; + if living_attacker { + chance = d.loot.equipment_drop_chance(&damage_params, chance); + } + let Some(mut stack) = stack else { continue }; + if d.loot.prevents_equipment_drop(&stack) || !(killed_by_player || preserve) { + continue; + } + if m.random.next_float() >= chance { + continue; + } + let max = d.loot.max_damage(&stack.item); + if !preserve && max > 0 { + let inner = m.random.next_int_bound((max - 3).max(1)).unwrap_or(0); + stack.damage = max - m.random.next_int_bound(1 + inner).unwrap_or(0); + } + out.push(Drop::Item(stack)); + clear_slot(m, slot); + } + // WitherBoss.dropCustomDeathLoot. + if s == Species::Wither { + out.push(Drop::Item(loot_stack("minecraft:nether_star", 1))); + } + } + // dropEquipment: AbstractHorse's inventory, then a chested horse's chest. + if equine::is_equine(s) { + for stack in m.extra.items.iter().flatten() { + if stack.count > 0 { + let mut item = loot_stack(&stack.item, stack.count as i32); + item.damage = stack.damage as i32; + out.push(Drop::Item(item)); + } + } + if m.extra.chested { + out.push(Drop::Item(loot_stack("minecraft:chest", 1))); + m.extra.chested = false; + } + } + // dropExperience. + let drops_experience = match s { + Species::Tadpole => false, + Species::Hoglin => true, + s if is_monster(s) => true, + _ => !m.is_baby(), + }; + if killed_by_player && drops_experience && d.mob_drops { + let mut amount = base_experience(m); + while amount > 0 { + let value = orb_value(amount); + amount -= value; + out.push(Drop::Orb(value)); + } + } + (out, skulls) +} +fn roll( + d: &Death, + table: &str, + params: &EntityLootParams, + sequences: &mut RandomSequences, +) -> Vec { + match d.loot.random_sequence(table) { + Some(id) => { + let random = sequences.get(id, d.world_seed); + d.loot.roll_entity(table, random, params) + } + None => Vec::new(), + } +} +/// `getBaseExperienceReward` (no vanilla enchantment changes mob experience). +pub fn base_experience(m: &mut Mob) -> i32 { + use Species as S; + let s = m.species(); + match s { + // Chicken.getBaseExperienceReward. + S::Chicken if m.extra.jockey => 10, + S::SulfurCube if m.is_baby() => 0, + S::SulfurCube => 1 + m.random.next_int_bound(2).unwrap_or(0), + // Hoglin / Piglin: the reward without the equipment bonus. + S::Hoglin | S::Piglin => xp_reward(m), + s if is_animal(s) || is_water_creature(s) => 1 + m.random.next_int_bound(3).unwrap_or(0), + _ => { + let mut reward = xp_reward(m); + // Zombie.getBaseExperienceReward: babies are worth 2.5 times as much. + if zombie_family(s) && m.is_baby() { + reward = (reward as f32 * 2.5) as i32; + } + if reward > 0 { + let mut result = reward; + for slot in SLOTS { + // EquipmentSlot.canIncreaseExperience: all but the saddle. + if slot != "saddle" && slot_item(m, slot).is_some() && drop_chance(m, slot) <= 1.0 { + result += 1 + m.random.next_int_bound(3).unwrap_or(0); + } + } + result + } else { + reward + } + } + } +} diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 9954298b9..899666265 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1443,7 +1443,6 @@ impl Def { | S::WitherSkeleton | S::ZombifiedPiglin | S::Zoglin - | S::Hoglin | S::Wither ), burns_in_day: matches!( diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index d36b00a79..b863e9659 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -1,10 +1,13 @@ -//! Container loot: `LootTable.fill` for chest-style loot tables (pools, +//! Loot tables: `LootTable.fill` for chest-style loot tables (pools, //! weighted entries, nested tables, item modifiers and conditions, the -//! stack splitter and the slot shuffle) with vanilla's random draw order. +//! stack splitter and the slot shuffle) and `LootTable.getRandomItems` for +//! entity loot (the victim, its killer, the damage source and the last +//! player to hurt it), with vanilla's random draw order. //! //! Items keep their id, count, damage, enchantments and potion. Exploration //! maps are kept as found (structure search is not run); conditions that -//! need an entity, tool or damage source fail, as they do for containers. +//! need an entity, tool or damage source fail when the context has none, as +//! they do for containers. use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{ @@ -41,6 +44,10 @@ impl LootStack { pub fn is_empty(&self) -> bool { self.count <= 0 || self.item == "minecraft:air" } + /// `ItemStack.getCount`: 0 for an empty stack. + pub fn get_count(&self) -> i32 { + if self.is_empty() { 0 } else { self.count } + } } #[derive(Clone, Copy, Debug, Default)] @@ -59,6 +66,10 @@ struct Enchantment { weight: i32, min_cost: (i32, i32), max_cost: (i32, i32), + /// `slots`: the equipment slot groups the enchantment works in. + slots: Vec, + /// `effects` (equipment_drops and others). + effects: Value, } impl Enchantment { fn min_cost(&self, level: i32) -> i32 { @@ -79,6 +90,134 @@ pub struct LootData { enchantments: Vec, /// Raw tag files by (registry, tag id). tags: HashMap<(String, String), Vec>, + /// Smelting recipes in recipe id order: (ingredient, result, result count). + smelting: Vec<(Value, String, i32)>, +} + +/// An entity a loot context names (`this`, `attacker`, `direct_attacker`, +/// `attacking_player`): the facts entity predicates read. +#[derive(Clone, Debug, Default)] +pub struct LootEntity { + /// Entity type id (`minecraft:zombie`). + pub kind: String, + /// A `LivingEntity` (has equipment and enchantment levels). + pub living: bool, + /// `Entity.isOnFire` (fire-immune entities never are). + pub on_fire: bool, + pub baby: bool, + /// The entity it rides (`getVehicle`). + pub vehicle: Option>, + /// `AbstractCubeMob.getSize`. + pub cube_size: Option, + /// A sheep's colour name and whether it is sheared. + pub sheep: Option<(String, bool)>, + /// A raider: whether it is a captain (wears the ominous banner). + pub captain: Option, + /// A frog's variant id (`minecraft:warm`). + pub frog_variant: Option, + /// A charged creeper (`Creeper.isPowered`). + pub powered: bool, + /// Worn and held items by `EquipmentSlot` name (mainhand, offhand, + /// feet, legs, chest, head, body, saddle). + pub equipment: Vec<(String, LootStack)>, +} +impl LootEntity { + pub fn new(kind: &str) -> Self { + Self { + kind: kind.to_owned(), + living: true, + ..Self::default() + } + } + pub fn item(&self, slot: &str) -> Option<&LootStack> { + self.equipment + .iter() + .find(|(s, i)| s == slot && !i.is_empty()) + .map(|(_, i)| i) + } +} +/// A `DamageSource`: its damage type and the entities behind it. +#[derive(Clone, Debug, Default)] +pub struct LootDamage { + /// Damage type id (`minecraft:player_attack`). + pub kind: String, + /// `getEntity`: the attacker (the shooter of a projectile). + pub source: Option, + /// `getDirectEntity`: the projectile, or the attacker itself. + pub direct: Option, +} +/// The parameters of `LivingEntity.dropFromLootTable`. +#[derive(Clone, Debug, Default)] +pub struct EntityLootParams { + pub this: LootEntity, + pub damage: Option, + /// `LAST_DAMAGE_PLAYER`: set when a player killed the entity. + pub player: Option, + /// The killing player's luck. + pub luck: f32, +} +/// `EquipmentSlot.VALUES` order. +pub const EQUIPMENT_SLOTS: [&str; 8] = [ + "mainhand", "offhand", "feet", "legs", "chest", "head", "body", "saddle", +]; +/// `EquipmentSlotGroup.test`. +fn slot_in_group(slot: &str, group: &str) -> bool { + match group { + "any" => true, + "hand" => slot == "mainhand" || slot == "offhand", + "armor" => matches!(slot, "feet" | "legs" | "chest" | "head" | "body"), + _ => slot == group, + } +} +/// `LevelBasedValue.calculate`. +pub fn level_value(v: &Value, level: i32) -> f32 { + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.) as f32, + Value::Object(_) => match v["type"].as_str().unwrap_or("") { + "minecraft:linear" => { + level_value(&v["base"], level) + + level_value(&v["per_level_above_first"], level) * (level - 1) as f32 + } + "minecraft:constant" => level_value(&v["value"], level), + "minecraft:clamped" => { + let value = level_value(&v["value"], level); + let min = v["min"].as_f64().unwrap_or(0.) as f32; + let max = v["max"].as_f64().unwrap_or(0.) as f32; + value.clamp(min, max) + } + "minecraft:fraction" => { + level_value(&v["numerator"], level) / level_value(&v["denominator"], level) + } + "minecraft:levels_squared" => { + (level * level) as f32 + v["added"].as_f64().unwrap_or(0.) as f32 + } + "minecraft:lookup" => { + let values = v["values"].as_array().map_or(&[][..], Vec::as_slice); + match values.get((level - 1).max(0) as usize) { + Some(x) if level >= 1 => x.as_f64().unwrap_or(0.) as f32, + _ => level_value(&v["fallback"], level), + } + } + _ => 0., + }, + _ => 0., + } +} +/// `MinMaxBounds.Ints.matches` (a number or `{min, max}`). +fn int_bounds(v: &Value, value: i32) -> bool { + match v { + Value::Null => true, + Value::Number(n) => n.as_i64() == Some(i64::from(value)), + Value::Object(o) => { + o.get("min") + .and_then(Value::as_i64) + .is_none_or(|m| i64::from(value) >= m) + && o.get("max") + .and_then(Value::as_i64) + .is_none_or(|m| i64::from(value) <= m) + } + _ => false, + } } fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap) -> io::Result<()> { @@ -150,11 +289,25 @@ impl LootData { weight: e["weight"].as_i64().unwrap_or(1) as i32, min_cost: cost(&e["min_cost"]), max_cost: cost(&e["max_cost"]), + slots: e["slots"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + effects: e["effects"].clone(), } }) .collect(); let mut tags = HashMap::new(); - for registry in ["item", "enchantment", "instrument"] { + for registry in [ + "item", + "enchantment", + "instrument", + "entity_type", + "damage_type", + ] { let mut raw = HashMap::new(); load_dir(&data.join("tags").join(registry), "", &mut raw)?; for (name, value) in raw { @@ -162,6 +315,20 @@ impl LootData { tags.insert((registry.to_owned(), name), values); } } + let mut recipes = HashMap::new(); + load_dir(&data.join("recipe"), "", &mut recipes)?; + let mut ids: Vec<&String> = recipes.keys().collect(); + ids.sort(); + let smelting = ids + .into_iter() + .map(|id| &recipes[id]) + .filter(|r| r["type"] == "minecraft:smelting") + .filter_map(|r| { + let result = r["result"]["id"].as_str()?.to_owned(); + let count = r["result"]["count"].as_i64().unwrap_or(1) as i32; + Some((r["ingredient"].clone(), result, count)) + }) + .collect(); Ok(Self { tables, modifiers, @@ -169,11 +336,82 @@ impl LootData { items, enchantments, tags, + smelting, }) } pub fn has_table(&self, table: &str) -> bool { self.tables.contains_key(table) } + /// The table's `random_sequence` (where `getRandomItems` draws from). + pub fn random_sequence(&self, table: &str) -> Option<&str> { + self.tables.get(table)?["random_sequence"].as_str() + } + pub fn max_stack(&self, item: &str) -> i32 { + self.facts(item).max_stack + } + pub fn max_damage(&self, item: &str) -> i32 { + self.facts(item).max_damage + } + /// Whether a registry tag (`entity_type`, `damage_type`, `item`...) holds `id`. + pub fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool { + self.tag(registry, tag).iter().any(|m| m == id) + } + /// `EnchantmentHelper.getEnchantmentLevel(enchantment, entity)`: the best + /// level on the items in the enchantment's slots. + pub fn enchantment_level(&self, enchantment: &str, entity: &LootEntity) -> i32 { + let Some(e) = self.enchantments.iter().find(|e| e.name == enchantment) else { + return 0; + }; + if !entity.living { + return 0; + } + EQUIPMENT_SLOTS + .iter() + .filter(|slot| e.slots.iter().any(|g| slot_in_group(slot, g))) + .filter_map(|slot| entity.item(slot)) + .map(|stack| item_level(stack, enchantment)) + .max() + .unwrap_or(0) + } + /// Whether an item carries an enchantment with `prevent_equipment_drop`. + pub fn prevents_equipment_drop(&self, stack: &LootStack) -> bool { + stack.enchantments.iter().any(|(name, _)| { + self.enchantments.iter().any(|e| { + &e.name == name && !e.effects["minecraft:prevent_equipment_drop"].is_null() + }) + }) + } + /// `EnchantmentHelper.processEquipmentDropChance`: the victim's and the + /// attacker's `equipment_drops` effects (Looting) applied to `chance`. + pub fn equipment_drop_chance(&self, params: &EntityLootParams, chance: f32) -> f32 { + // Enchantment.damageContext: no luck and no killing player. + let damage_params = EntityLootParams { + this: params.this.clone(), + damage: params.damage.clone(), + player: None, + luck: 0.0, + }; + let mut c = Context { + data: self, + random: LegacyRandom::new(0), + biome: None, + visited: Vec::new(), + luck: 0.0, + open_water: None, + entity: Some(&damage_params), + }; + let mut chance = chance; + c.equipment_drops(¶ms.this, "victim", &mut chance); + if let Some(attacker) = params + .damage + .as_ref() + .and_then(|d| d.source.as_ref()) + .filter(|a| a.living) + { + c.equipment_drops(attacker, "attacker", &mut chance); + } + chance + } /// Tag members in tag order (nested tags expanded in place, duplicates /// dropped). fn tag(&self, registry: &str, name: &str) -> Vec { @@ -246,12 +484,54 @@ impl LootData { visited: Vec::new(), luck, open_water, + entity: None, }; let mut items = Vec::new(); c.table_raw(table, json, &mut |_, stack| items.push(stack)); *random = c.random; items } + /// LootTable.getRandomItems for an entity context: the generated stacks + /// after the stack splitter, in order. `random` is the table's random + /// sequence (or the level random) and is advanced. + pub fn roll_entity( + &self, + table: &str, + random: &mut R, + params: &EntityLootParams, + ) -> Vec { + let Some(json) = self.tables.get(table) else { + return Vec::new(); + }; + let mut c = Context { + data: self, + random: random.clone(), + biome: None, + visited: Vec::new(), + luck: params.luck, + open_water: None, + entity: Some(params), + }; + let mut items = Vec::new(); + c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); + *random = c.random; + items + } + /// LootTable.createStackSplitter (every item is enabled). + fn split(&self, stack: LootStack, items: &mut Vec) { + let max = self.facts(&stack.item).max_stack.max(1); + if stack.count < max { + items.push(stack); + } else { + let mut count = stack.count; + while count > 0 { + let mut copy = stack.clone(); + copy.count = max.min(count); + count -= copy.count; + items.push(copy); + } + } + } /// LootTable.fill into an empty container of `slots` slots with /// `RandomSource.create(seed)`; `biome` is the container's biome for /// location checks (None: no origin, checks fail). @@ -273,23 +553,10 @@ impl LootData { visited: Vec::new(), luck: 0.0, open_water: None, + entity: None, }; let mut items = Vec::new(); - c.table_raw(table, json, &mut |c, stack| { - // LootTable.createStackSplitter (every item is enabled). - let max = c.data.facts(&stack.item).max_stack.max(1); - if stack.count < max { - items.push(stack); - } else { - let mut count = stack.count; - while count > 0 { - let mut copy = stack.clone(); - copy.count = max.min(count); - count -= copy.count; - items.push(copy); - } - } - }); + c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); let random = &mut c.random; let mut available: Vec = (0..slots).collect(); shuffle(&mut available, random); @@ -302,15 +569,23 @@ impl LootData { } } +/// The level of one enchantment on a stack (its `enchantments` component). +fn item_level(stack: &LootStack, enchantment: &str) -> i32 { + stack + .enchantments + .iter() + .find(|(n, _)| n == enchantment) + .map_or(0, |(_, l)| *l) +} /// Util.shuffle. -fn shuffle(list: &mut [T], random: &mut LegacyRandom) { +fn shuffle(list: &mut [T], random: &mut impl RandomSource) { for i in (2..=list.len()).rev() { let j = random.next_int_bound(i as i32).unwrap_or(0) as usize; list.swap(i - 1, j); } } /// Mth.nextInt. -fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 { +fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> i32 { if min >= max { min } else { @@ -353,19 +628,136 @@ fn shuffle_and_split(result: &mut Vec, slots: usize, random: &mut Leg shuffle(result, random); } -struct Context<'a> { +struct Context<'a, R> { data: &'a LootData, - random: LegacyRandom, + random: R, biome: Option<&'a str>, visited: Vec, /// LootContext.getLuck. luck: f32, /// A fishing hook's `is_open_water` for `entity_properties` (None: no entity). open_water: Option, + /// The entity, damage source and killer parameters. + entity: Option<&'a EntityLootParams>, } -type Sink<'s> = dyn FnMut(&mut Context<'_>, LootStack) + 's; +type Sink<'s, R> = dyn FnMut(&mut Context<'_, R>, LootStack) + 's; -impl Context<'_> { +impl Context<'_, R> { + /// A `LootContext.EntityTarget` parameter. + fn target(&self, name: &str) -> Option<&LootEntity> { + let p = self.entity?; + match name { + "this" => Some(&p.this), + "attacker" => p.damage.as_ref()?.source.as_ref(), + "direct_attacker" => p.damage.as_ref()?.direct.as_ref(), + "attacking_player" => p.player.as_ref(), + _ => None, + } + } + /// The `ATTACKING_ENTITY` parameter when it is a living entity. + fn living_attacker(&self) -> Option<&LootEntity> { + self.target("attacker").filter(|a| a.living) + } + /// The `equipment_drops` effects on one entity's equipment + /// (`runIterationOnEquipment`), for the given `enchanted` target. + fn equipment_drops(&mut self, holder: &LootEntity, enchanted: &str, chance: &mut f32) { + let data = self.data; + for slot in EQUIPMENT_SLOTS { + let Some(stack) = holder.item(slot) else { + continue; + }; + for (name, level) in &stack.enchantments { + let Some(e) = data.enchantments.iter().find(|e| &e.name == name) else { + continue; + }; + if !e.slots.iter().any(|g| slot_in_group(slot, g)) { + continue; + } + for effect in e.effects["minecraft:equipment_drops"] + .as_array() + .into_iter() + .flatten() + { + if effect["enchanted"].as_str() != Some(enchanted) + || effect["affected"].as_str().unwrap_or("victim") != "victim" + { + continue; + } + if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) { + continue; + } + let value = level_value(&effect["effect"]["value"], *level); + *chance = match effect["effect"]["type"].as_str().unwrap_or("") { + "minecraft:add" => *chance + value, + "minecraft:multiply" => *chance * value, + "minecraft:set" => value, + _ => *chance, + }; + } + } + } + } + /// EntityPredicate.matches (false without an entity). + fn entity_matches(&self, p: &Value, e: Option<&LootEntity>) -> bool { + let Some(e) = e else { return false }; + let Some(parts) = p.as_object() else { + return true; + }; + let data = self.data; + parts.iter().all(|(key, v)| match key.as_str() { + "minecraft:entity_type" => match v.as_str() { + Some(s) => match s.strip_prefix('#') { + Some(tag) => data.in_tag("entity_type", tag, &e.kind), + None => s == e.kind, + }, + None => v + .as_array() + .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(&e.kind))), + }, + "minecraft:flags" => v.as_object().into_iter().flatten().all(|(flag, want)| { + let want = want.as_bool().unwrap_or(false); + match flag.as_str() { + "is_on_fire" => e.on_fire == want, + // EntityFlagsPredicate: only living entities have an age. + "is_baby" => !e.living || e.baby == want, + "is_fall_flying" => !e.living || !want, + _ => !want, + } + }), + "minecraft:equipment" => { + e.living + && v.as_object().into_iter().flatten().all(|(slot, item)| { + e.item(slot) + .is_some_and(|stack| self.item_matches(item, stack)) + }) + } + "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| { + match c.as_str() { + "minecraft:sheep/color" => e + .sheep + .as_ref() + .is_some_and(|(color, _)| want.as_str() == Some(color)), + "minecraft:frog/variant" => { + e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() + } + _ => false, + } + }), + "minecraft:type_specific/sheep" => e.sheep.as_ref().is_some_and(|(_, sheared)| { + v["sheared"].as_bool().is_none_or(|w| w == *sheared) + }), + "minecraft:type_specific/cube_mob" => { + e.cube_size.is_some_and(|size| int_bounds(&v["size"], size)) + } + // RaiderPredicate: no raid is running here. + "minecraft:type_specific/raider" => e.captain.is_some_and(|captain| { + !v["has_raid"].as_bool().unwrap_or(false) + && captain == v["is_captain"].as_bool().unwrap_or(false) + }), + "minecraft:vehicle" => self.entity_matches(v, e.vehicle.as_deref()), + _ => false, + }) + } fn int(&mut self, v: &Value) -> i32 { match v { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, @@ -426,16 +818,62 @@ impl Context<'_> { .into_iter() .flatten() .any(|t| self.condition(t)), + "minecraft:entity_properties" if self.entity.is_some() => { + let target = self.target(c["entity"].as_str().unwrap_or("this")); + c["predicate"].is_null() || self.entity_matches(&c["predicate"], target) + } // FishingHookPredicate: the only entity property a hook has. "minecraft:entity_properties" => { - let fishing = &c["predicate"]["type_specific"]; - match (self.open_water, fishing["type"].as_str()) { - (Some(open), Some("minecraft:fishing_hook")) => fishing["in_open_water"] + let predicate = &c["predicate"]; + let fishing = &predicate["minecraft:type_specific/fishing_hook"]; + let only_hook = predicate.as_object().is_some_and(|o| o.len() == 1); + match self.open_water { + Some(open) if only_hook && fishing.is_object() => fishing["in_open_water"] .as_bool() .is_none_or(|want| want == open), _ => false, } } + "minecraft:killed_by_player" => self.entity.is_some_and(|p| p.player.is_some()), + "minecraft:random_chance_with_enchanted_bonus" => { + let level = self.living_attacker().map_or(0, |a| { + data.enchantment_level(c["enchantment"].as_str().unwrap_or(""), a) + }); + let chance = if level > 0 { + level_value(&c["enchanted_chance"], level) + } else { + c["unenchanted_chance"].as_f64().unwrap_or(0.) as f32 + }; + self.random.next_float() < chance + } + // DamageSourcePredicate (false without a damage source). + "minecraft:damage_source_properties" => { + let Some(damage) = self.entity.and_then(|p| p.damage.as_ref()) else { + return false; + }; + let p = &c["predicate"]; + let tags_ok = p["tags"].as_array().into_iter().flatten().all(|t| { + let id = t["id"].as_str().unwrap_or(""); + let has = match id.strip_prefix('#') { + Some(tag) => data.in_tag("damage_type", tag, &damage.kind), + None => id == damage.kind, + }; + has == t["expected"].as_bool().unwrap_or(false) + }); + tags_ok + && (p["direct_entity"].is_null() + || self.entity_matches(&p["direct_entity"], damage.direct.as_ref())) + && (p["source_entity"].is_null() + || self.entity_matches(&p["source_entity"], damage.source.as_ref())) + && p["is_direct"].as_bool().is_none_or(|want| { + let direct = match (&damage.source, &damage.direct) { + (Some(a), Some(b)) => a.kind == b.kind, + (None, None) => true, + _ => false, + }; + direct == want + }) + } "minecraft:random_chance" => { let chance = self.float(&c["chance"]); self.random.next_float() < chance @@ -489,7 +927,7 @@ impl Context<'_> { } "minecraft:set_count" => { let base = if f["add"].as_bool() == Some(true) { - stack.count + stack.get_count() } else { 0 }; @@ -497,12 +935,14 @@ impl Context<'_> { } "minecraft:limit_count" => { let limit = &f["limit"]; + let mut count = stack.get_count(); if let Some(min) = limit["min"].as_i64() { - stack.count = stack.count.max(min as i32); + count = count.max(min as i32); } if let Some(max) = limit["max"].as_i64() { - stack.count = stack.count.min(max as i32); + count = count.min(max as i32); } + stack.count = count; } "minecraft:set_damage" => { let max = data.facts(&stack.item).max_damage; @@ -611,19 +1051,74 @@ impl Context<'_> { stack = self.modify(branch, stack); } "minecraft:discard" => stack.count = 0, + "minecraft:enchanted_count_increase" => { + if let Some(attacker) = self.living_attacker() { + let level = + data.enchantment_level(f["enchantment"].as_str().unwrap_or(""), attacker); + if level != 0 { + let addition = level as f32 * self.float(&f["count"]); + // ItemStack.grow(Math.round(addition)). + stack.count = stack.get_count() + (addition + 0.5).floor() as i32; + let limit = f["limit"].as_i64().unwrap_or(0) as i32; + if limit > 0 && !stack.is_empty() && stack.count > limit { + stack.count = limit; + } + } + } + } + "minecraft:furnace_smelt" => { + if !stack.is_empty() + && let Some((_, result, count)) = data + .smelting + .iter() + .find(|(ingredient, _, _)| data.item_in(&stack.item, ingredient)) + { + let input = if f["use_input_count"].as_bool().unwrap_or(true) { + stack.count + } else { + 1 + }; + let mut smelted = LootStack::new(result); + smelted.count = (input * count).min(data.facts(result).max_stack); + stack = smelted; + } + } // Names, lore, components and other data without random draws. _ => {} } stack } - /// ItemPredicate subset used by filtered modifiers. + /// ItemPredicate subset used by filtered modifiers and equipment. fn item_matches(&self, p: &Value, stack: &LootStack) -> bool { if !p["items"].is_null() && !self.data.item_in(&stack.item, &p["items"]) { return false; } + if !int_bounds(&p["count"], stack.count) { + return false; + } if p["predicates"].get("minecraft:map_id").is_some() && !stack.map { return false; } + // EnchantmentsPredicate: every entry must hold. + if let Some(list) = p["predicates"]["minecraft:enchantments"].as_array() { + let data = self.data; + let ok = list.iter().all(|e| { + let levels = &e["levels"]; + match &e["enchantments"] { + Value::Null => stack + .enchantments + .iter() + .any(|(_, l)| int_bounds(levels, *l)), + set => data.holder_set("enchantment", set).iter().any(|name| { + let level = item_level(stack, name); + level != 0 && int_bounds(levels, level) + }), + } + }); + if !ok { + return false; + } + } true } /// EnchantmentHelper.selectEnchantment. @@ -662,7 +1157,7 @@ impl Context<'_> { if available.is_empty() { return results; } - let pick = |random: &mut LegacyRandom, list: &[(usize, i32)]| -> Option<(usize, i32)> { + let pick = |random: &mut R, list: &[(usize, i32)]| -> Option<(usize, i32)> { let total: i32 = list.iter().map(|&(i, _)| data.enchantments[i].weight).sum(); if total <= 0 { return None; @@ -702,7 +1197,7 @@ impl Context<'_> { .contains(&ea.name) } /// LootTable.getRandomItemsRaw. - fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_>) { + fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_, R>) { if self.visited.iter().any(|v| v == name) { return; } @@ -729,14 +1224,15 @@ impl Context<'_> { self.visited.pop(); } /// LootPool.addRandomItem. - fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_>) { - let mut valid: Vec<&Value> = Vec::new(); + fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_, R>) { + let mut valid: Vec> = Vec::new(); for entry in pool["entries"].as_array().into_iter().flatten() { self.expand(entry, &mut valid); } // EntryBase.getWeight: max(floor(weight + quality * luck), 0). let luck = self.luck; - let weight = |e: &Value| { + let weight = |c: &Choice<'_>| { + let e = c.entry; let w = e["weight"].as_i64().unwrap_or(1) as f32 + e["quality"].as_i64().unwrap_or(0) as f32 * luck; w.floor().max(0.0) as i32 @@ -746,21 +1242,21 @@ impl Context<'_> { return; } let chosen = if valid.len() == 1 { - valid[0] + valid.swap_remove(0) } else { let mut index = self.random.next_int_bound(total).unwrap_or(0); - let Some(e) = valid.iter().find(|e| { + let Some(at) = valid.iter().position(|e| { index -= weight(e); index < 0 }) else { return; }; - e + valid.swap_remove(at) }; - self.create(chosen, sink); + self.create(&chosen, sink); } /// LootPoolEntryContainer.expand: the singleton entries that can run. - fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec<&'v Value>) -> bool { + fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec>) -> bool { if !entry["condition"].is_null() && !self.condition(&entry["condition"]) { return false; } @@ -783,17 +1279,35 @@ impl Context<'_> { } "minecraft:item" | "minecraft:empty" | "minecraft:loot_table" => { if entry["weight"].as_i64().unwrap_or(1) > 0 { - out.push(entry); + out.push(Choice { entry, item: None }); } true } + // TagEntry: one choice per item when expanded, else one for all. + "minecraft:tag" => { + if entry["expand"].as_bool().unwrap_or(false) { + let items = self.data.holder_set("item", &entry["items"]); + for item in items { + if entry["weight"].as_i64().unwrap_or(1) > 0 { + out.push(Choice { entry, item: Some(item) }); + } + } + true + } else { + if entry["weight"].as_i64().unwrap_or(1) > 0 { + out.push(Choice { entry, item: None }); + } + true + } + } _ => false, } } /// LootPoolEntry.createItemStack with the entry's modifier. - fn create(&mut self, entry: &Value, sink: &mut Sink<'_>) { + fn create(&mut self, choice: &Choice<'_>, sink: &mut Sink<'_, R>) { + let entry = choice.entry; let modifier = &entry["modifier"]; - let mut out = |c: &mut Context<'_>, stack: LootStack| { + let mut out = |c: &mut Context<'_, R>, stack: LootStack| { let stack = c.modify(modifier, stack); sink(c, stack); }; @@ -802,6 +1316,14 @@ impl Context<'_> { let stack = LootStack::new(entry["name"].as_str().unwrap_or("minecraft:air")); out(self, stack); } + "minecraft:tag" => match &choice.item { + Some(item) => out(self, LootStack::new(item)), + None => { + for item in self.data.holder_set("item", &entry["items"]) { + out(self, LootStack::new(&item)); + } + } + }, "minecraft:loot_table" => match &entry["value"] { Value::String(name) => { if let Some(table) = self.data.tables.get(name) { @@ -815,6 +1337,11 @@ impl Context<'_> { } } } +/// A pool entry that can be chosen (an expanded tag entry names its item). +struct Choice<'v> { + entry: &'v Value, + item: Option, +} fn enchant(stack: &mut LootStack, name: &str, level: i32) { match stack.enchantments.iter_mut().find(|(n, _)| n == name) { Some(slot) => slot.1 = level, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java new file mode 100644 index 000000000..bffe88e56 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java @@ -0,0 +1,320 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.RandomSequences; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.damagesource.DamageSources; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.phys.AABB; + +/** + * Original oracle: entity death drops. Each input line describes a victim, its + * equipment and state, a killer and a damage source; the oracle creates the + * real entities on a stand-in ServerLevel (whose addFreshEntity records the + * spawned item entities and experience orbs) and runs LivingEntity.die's drop + * step: the source entity's killedEntity hook, then dropAllDeathLoot (loot + * table with the world's random sequence, dropCustomDeathLoot with the entity + * random, dropEquipment, dropExperience). Loot table randoms come from a fresh + * RandomSequences per case; each case kills `kills` identical victims in turn. + */ +public final class VanillaEntityDeathLootOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + long offset = (long) objectFieldOffset.invoke(unsafe, f); + putObject.invoke(unsafe, target, offset, value); + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + MinecraftServer fake; + RegistryAccess registries; + GameRules rules; + List out; + int next = 1; + @Override public MinecraftServer getServer() { return fake; } + @Override public RegistryAccess registryAccess() { return registries; } + @Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; } + @Override public long getGameTime() { return 0L; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public GameRules getGameRules() { return rules; } + @Override public boolean addFreshEntity(Entity entity) { + if (entity instanceof ItemEntity item) out.add("drop " + stack(item.getItem())); + else if (entity instanceof ExperienceOrb orb) out.add("orb " + orb.getValue()); + else out.add("entity " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())); + return true; + } + @Override public List getEntities(EntityTypeTest type, AABB bb, Predicate selector) { return new ArrayList<>(); } + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public int getSeaLevel() { return 63; } + @Override public net.minecraft.world.entity.raid.Raid getRaidAt(BlockPos pos) { return null; } + @Override public net.minecraft.world.level.BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return null; } + @Override public List getEntityCollisions(Entity source, AABB area) { return List.of(); } + @Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); } + } + + static final class OraclePlayer extends Player { + OraclePlayer(Level level) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); } + @Override public GameType gameMode() { return GameType.SURVIVAL; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); } + } + + static String stack(ItemStack stack) { + StringBuilder line = new StringBuilder(BuiltInRegistries.ITEM.getKey(stack.getItem()) + " " + stack.getCount()); + if (stack.getDamageValue() != 0) line.append(" damage=").append(stack.getDamageValue()); + var enchantments = stack.getOrDefault(DataComponents.ENCHANTMENTS, net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY); + for (var e : enchantments.entrySet()) line.append(" ench=").append(e.getKey().unwrapKey().get().identifier()).append(':').append(e.getIntValue()); + var potion = stack.get(DataComponents.POTION_CONTENTS); + if (potion != null && potion.potion().isPresent()) line.append(" potion=").append(potion.potion().get().unwrapKey().get().identifier()); + var ominous = stack.get(DataComponents.OMINOUS_BOTTLE_AMPLIFIER); + if (ominous != null) line.append(" ominous=").append(ominous.value()); + return line.toString(); + } + + static Map parse(String line) { + Map m = new LinkedHashMap<>(); + for (String token : line.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) m.put("name", token); else m.put(token.substring(0, eq), token.substring(eq + 1)); + } + return m; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + RegistryAccess access = loaded.layers().compositeAccess(); + + // A server that only answers reloadableRegistries, getRandomSequence and debug subscribers. + MinecraftServer server = (MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class); + put(server, MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class)); + ReloadableServerResources managers = (ReloadableServerResources) alloc(ReloadableServerResources.class); + put(managers, ReloadableServerResources.class, "fullRegistryHolder", new ReloadableServerRegistries.Holder(lookup)); + Class holderRecord = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources"); + Constructor rr = holderRecord.getDeclaredConstructors()[0]; + rr.setAccessible(true); + put(server, MinecraftServer.class, "resources", rr.newInstance(null, managers)); + var recipes = new net.minecraft.world.item.crafting.RecipeManager(lookup); + recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(managers, ReloadableServerResources.class, "recipes", recipes); + put(server, MinecraftServer.class, "scoreboard", new net.minecraft.server.ServerScoreboard(server)); + + Lvl level = (Lvl) alloc(Lvl.class); + level.fake = server; + level.registries = access; + put(level, ServerLevel.class, "server", server); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(level, Level.class, "damageSources", new DamageSources(access)); + put(level, Level.class, "random", RandomSource.create(0L)); + Method dropAll = LivingEntity.class.getDeclaredMethod("dropAllDeathLoot", ServerLevel.class, DamageSource.class); + dropAll.setAccessible(true); + var enchantments = access.lookupOrThrow(Registries.ENCHANTMENT); + + if (args.length > 2 && args[2].equals("facts")) { + // Per-type facts the death step reads (a debugging aid, not compared). + Field xp = Mob.class.getDeclaredField("xpReward"); + xp.setAccessible(true); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (var type : BuiltInRegistries.ENTITY_TYPE) { + Entity e; + try { e = type.create(level, EntitySpawnReason.LOAD); } catch (Throwable t) { continue; } + if (!(e instanceof Mob mob)) continue; + StringBuilder sb = new StringBuilder(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString()); + sb.append(" monster=").append(e instanceof net.minecraft.world.entity.monster.Monster).append(" xp=").append(xp.get(mob)) + .append(" baby=").append(mob.isBaby()).append(" class=").append(e.getClass().getSimpleName()) + .append(" animal=").append(e instanceof net.minecraft.world.entity.animal.Animal) + .append(" agwater=").append(e instanceof net.minecraft.world.entity.animal.AgeableWaterCreature) + .append(" water=").append(e instanceof net.minecraft.world.entity.animal.fish.WaterAnimal) + .append(" ageable=").append(e instanceof AgeableMob); + mob.setBaby(true); + sb.append(" canbaby=").append(mob.isBaby()); + for (EquipmentSlot slot : EquipmentSlot.VALUES) if (mob.getDropChances().byEquipment(slot) != 0.085F) sb.append(' ').append(slot.getName()).append('=').append(mob.getDropChances().byEquipment(slot)); + w.println(sb); + } + } + System.exit(0); + } + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String raw : lines) { + if (raw.isBlank() || raw.startsWith("#")) continue; + Map c = parse(raw); + w.println("== " + c.get("name")); + List out = new ArrayList<>(); + level.out = out; + try { + long worldSeed = Long.parseLong(c.getOrDefault("seed", "0")); + put(server, MinecraftServer.class, "worldGenSettings", new WorldGenSettings(new WorldOptions(worldSeed, false, false), null)); + put(server, MinecraftServer.class, "randomSequences", new RandomSequences()); + int kills = Integer.parseInt(c.getOrDefault("kills", "1")); + long rand = Long.parseLong(c.getOrDefault("rand", "0")); + for (int k = 0; k < kills; k++) { + out.add("kill " + k); + run(level, access, enchantments, c, rand + k, dropAll); + } + } catch (Throwable t) { + Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t; + StringBuilder trace = new StringBuilder("error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) trace.append("\n at ").append(frame); + out.add(trace.toString()); + } + out.forEach(w::println); + } + } + System.exit(0); + } + + static ItemStack item(HolderLookup.RegistryLookup enchantments, String spec) { + // id[;enchantment:level...] + String[] parts = spec.split(";"); + ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(parts[0]))); + for (int i = 1; i < parts.length; i++) { + int colon = parts[i].lastIndexOf(':'); + String name = parts[i].substring(0, colon); + if (!name.contains(":")) name = "minecraft:" + name; + stack.enchant(enchantments.getOrThrow(ResourceKey.create(Registries.ENCHANTMENT, Identifier.parse(name))), Integer.parseInt(parts[i].substring(colon + 1))); + } + return stack; + } + + static Entity create(Lvl level, String id) { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(id)); + return type.create(level, EntitySpawnReason.LOAD); + } + + @SuppressWarnings("unchecked") + static void run(Lvl level, RegistryAccess access, HolderLookup.RegistryLookup enchantments, + Map c, long rand, Method dropAll) throws Exception { + LivingEntity victim = (LivingEntity) create(level, c.get("type")); + victim.setPos(0.5, 64.0, 0.5); + if (c.containsKey("baby") && victim instanceof Mob mob) mob.setBaby(c.get("baby").equals("1")); + if (c.getOrDefault("fire", "0").equals("1")) victim.setRemainingFireTicks(100); + if (c.containsKey("size")) victim.getClass().getMethod("setSize", int.class, boolean.class).invoke(victim, Integer.parseInt(c.get("size")), true); + if (c.containsKey("color") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setColor(DyeColor.byName(c.get("color"), DyeColor.WHITE)); + if (c.getOrDefault("sheared", "0").equals("1") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true); + if (c.getOrDefault("leader", "0").equals("1")) ((net.minecraft.world.entity.monster.PatrollingMonster) victim).setPatrolLeader(true); + if (c.getOrDefault("captain", "0").equals("1")) + victim.setItemSlot(EquipmentSlot.HEAD, net.minecraft.world.entity.raid.Raid.getOminousBannerInstance(access.lookupOrThrow(Registries.BANNER_PATTERN))); + for (EquipmentSlot slot : EquipmentSlot.VALUES) { + String spec = c.get(slot.getName()); + if (spec != null) victim.setItemSlot(slot, item(enchantments, spec)); + String chance = c.get("chance_" + slot.getName()); + if (chance != null && victim instanceof Mob mob) mob.setDropChance(slot, Float.parseFloat(chance)); + } + if (c.containsKey("vehicle")) { + Entity vehicle = create(level, c.get("vehicle")); + vehicle.setPos(0.5, 64.0, 0.5); + if (!victim.startRiding(vehicle, true, false)) throw new IllegalStateException("could not ride"); + } + // Killer and damage source. + Player player = null; + LivingEntity killer = null; + String killerId = c.getOrDefault("killer", "none"); + if (killerId.equals("player") || c.getOrDefault("pkill", "0").equals("1")) { + player = new OraclePlayer(level); + player.setPos(2.5, 64.0, 0.5); + if (c.containsKey("luck")) player.getAttribute(Attributes.LUCK).setBaseValue(Double.parseDouble(c.get("luck"))); + if (killerId.equals("player") && c.containsKey("weapon")) player.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon"))); + } + if (killerId.equals("player")) killer = player; + else if (!killerId.equals("none")) { + killer = (LivingEntity) create(level, killerId); + killer.setPos(2.5, 64.0, 0.5); + if (c.containsKey("weapon")) killer.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon"))); + if (c.containsKey("frog")) killer.setComponent(DataComponents.FROG_VARIANT, + access.lookupOrThrow(Registries.FROG_VARIANT).getOrThrow(ResourceKey.create(Registries.FROG_VARIANT, Identifier.parse(c.get("frog"))))); + if (c.getOrDefault("charged", "0").equals("1")) { + Field powered = net.minecraft.world.entity.monster.Creeper.class.getDeclaredField("DATA_IS_POWERED"); + powered.setAccessible(true); + killer.getEntityData().set((net.minecraft.network.syncher.EntityDataAccessor) powered.get(null), true); + } + } + if (player != null && c.getOrDefault("pkill", killerId.equals("player") ? "1" : "0").equals("1")) victim.setLastHurtByPlayer(player, 100); + DamageSources sources = level.damageSources(); + DamageSource source = switch (c.getOrDefault("source", "attack")) { + case "attack" -> killer == null ? sources.generic() : killer instanceof Player p ? sources.playerAttack(p) : sources.mobAttack(killer); + case "arrow" -> { + var arrow = new net.minecraft.world.entity.projectile.arrow.Arrow(EntityTypes.ARROW, level); + arrow.setPos(1.5, 64.0, 0.5); + yield sources.arrow(arrow, killer); + } + case "fireball" -> { + var fireball = new net.minecraft.world.entity.projectile.hurtingprojectile.LargeFireball(EntityTypes.FIREBALL, level); + fireball.setPos(1.5, 64.0, 0.5); + yield sources.fireball(fireball, killer); + } + case "explosion" -> sources.explosion(killer, killer); + case "lightning" -> sources.lightningBolt(); + case "fire" -> sources.onFire(); + default -> sources.generic(); + }; + victim.getRandom().setSeed(rand); + Entity sourceEntity = source.getEntity(); + if (sourceEntity == null || sourceEntity.killedEntity(level, victim, source)) dropAll.invoke(victim, level, source); + } +} diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py new file mode 100644 index 000000000..ecbd2c7c8 --- /dev/null +++ b/tools/test_entity_death_loot_parity.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Compare entity death drops (loot tables, equipment drops, experience) with vanilla. + +Java (VanillaEntityDeathLootOracle) builds the real victim, killer and damage +source on a stand-in ServerLevel and runs LivingEntity.die's drop step; Rust +(entity_death_loot_fixture) runs horizon_client::mobs::drops on the same cases. +Every living entity type with a loot table is killed by a player with and +without looting, by nothing, on fire, with a smelting weapon, as a baby, with +luck and with worn equipment, plus each table's special conditions (sheep +colours, cube sizes, frog kills, skeleton and charged creeper kills, fireballs, +lightning, raid captains and vehicles). Loot draws come from the world's random +sequences; several victims are killed in turn per case. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +# Living entity types with an entity loot table that the corpus skips: players +# and stands are not mobs, the dragon dies over 200 ticks, and the giant and +# the copper golem are not Horizon mob types. +SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'} +# Types Horizon keeps body armour for in the head slot: their corpus wears +# body items instead of helmets. +BODY = {'horse', 'donkey', 'mule', 'skeleton_horse', 'zombie_horse', 'camel', 'camel_husk', 'llama', 'trader_llama', + 'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube'} +WEAPONS = ['minecraft:iron_sword', 'minecraft:diamond_sword;looting:1', 'minecraft:diamond_sword;looting:2', + 'minecraft:netherite_sword;looting:3', 'minecraft:golden_sword;fire_aspect:2', 'minecraft:diamond_axe;looting:3;fire_aspect:1'] +ARMOUR = {'head': 'minecraft:iron_helmet', 'chest': 'minecraft:chainmail_chestplate', 'legs': 'minecraft:golden_leggings', + 'feet': 'minecraft:diamond_boots', 'mainhand': 'minecraft:iron_sword', 'offhand': 'minecraft:shield'} +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def corpus(types): + rng = random.Random(0x4C4F4F54) + cases = [] + + def add(name, **kv): + kv.setdefault('seed', rng.randrange(-2**63, 2**63)) + kv.setdefault('rand', rng.randrange(-2**47, 2**47)) + cases.append(name + ''.join(f' {k}={v}' for k, v in kv.items())) + for t in types: + n = t.split(':')[1] + add(f'{n}-player', type=t, killer='player', weapon='minecraft:iron_sword', kills=4) + add(f'{n}-none', type=t, source='generic', kills=3) + add(f'{n}-mob', type=t, killer='minecraft:spider', kills=2) + for i, weapon in enumerate(WEAPONS[1:]): + add(f'{n}-weapon{i}', type=t, killer='player', weapon=weapon, kills=4) + add(f'{n}-fire', type=t, killer='player', fire=1, kills=3) + add(f'{n}-fire-nokill', type=t, fire=1, source='fire', kills=2) + add(f'{n}-baby', type=t, killer='player', baby=1, weapon='minecraft:iron_sword;looting:3', kills=3) + add(f'{n}-luck', type=t, killer='player', luck=rng.choice([1, 2, 5]), kills=3) + add(f'{n}-arrow', type=t, killer='player', source='arrow', weapon='minecraft:bow;looting:3', kills=2) + head = 'body' if n in BODY else 'head' + armour = dict(ARMOUR) + if n in BODY: + armour['body'] = armour.pop('head').replace('helmet', 'horse_armor') + add(f'{n}-gear', type=t, killer='player', weapon='minecraft:iron_sword;looting:3', kills=6, **armour) + add(f'{n}-gear-plain', type=t, killer='player', kills=6, mainhand='minecraft:stone_axe', chance_mainhand=0.5, + **{head: 'minecraft:leather_helmet', f'chance_{head}': 2.0}) + add(f'{n}-gear-nokill', type=t, source='generic', kills=4, feet='minecraft:iron_boots', chance_feet=1.0, + **{head: 'minecraft:carved_pumpkin', f'chance_{head}': 2.0}) + add(f'{n}-gear-mob', type=t, killer='minecraft:skeleton', source='arrow', kills=4, feet='minecraft:iron_boots', chance_feet=1.0, + weapon='minecraft:bow;looting:3') + for color in DYES: + add(f'sheep-{color}', type='minecraft:sheep', color=color, killer='player', kills=3) + add(f'sheep-{color}-sheared', type='minecraft:sheep', color=color, sheared=1, killer='player', kills=2) + for cube in ['minecraft:slime', 'minecraft:magma_cube', 'minecraft:sulfur_cube']: + for size in [1, 2, 3, 4]: + add(f'{cube[10:]}-size{size}', type=cube, size=size, killer='player', weapon='minecraft:iron_sword;looting:2', kills=4) + for frog in ['temperate', 'warm', 'cold']: + for size in [1, 2, 4]: + add(f'magma_cube-frog-{frog}-{size}', type='minecraft:magma_cube', size=size, killer='minecraft:frog', frog='minecraft:' + frog, + pkill=rng.choice([0, 1]), kills=3) + add('creeper-skeleton', type='minecraft:creeper', killer='minecraft:skeleton', source='arrow', pkill=1, kills=3) + add('creeper-stray', type='minecraft:creeper', killer='minecraft:stray', source='arrow', kills=2) + for victim in ['zombie', 'skeleton', 'creeper', 'wither_skeleton', 'piglin', 'zombie_villager', 'cow']: + add(f'charged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', charged=1, source='explosion', kills=2) + add(f'uncharged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', source='explosion', kills=2) + add('ghast-fireball', type='minecraft:ghast', killer='player', source='fireball', kills=4) + add('ghast-fireball-ghast', type='minecraft:ghast', killer='minecraft:ghast', source='fireball', kills=2) + add('turtle-lightning', type='minecraft:turtle', source='lightning', kills=3) + add('turtle-lightning-player', type='minecraft:turtle', source='lightning', pkill=1, kills=3) + add('pillager-captain', type='minecraft:pillager', captain=1, leader=1, killer='player', kills=3) + add('pillager-captain-none', type='minecraft:pillager', captain=1, leader=1, source='generic', kills=2) + add('pillager-captain-looting', type='minecraft:pillager', captain=1, leader=1, killer='player', + weapon='minecraft:iron_sword;looting:3', kills=4, chance_head=2.0) + add('pillager-banner-only', type='minecraft:pillager', captain=1, killer='player', kills=3) + add('pillager-leader-only', type='minecraft:pillager', leader=1, killer='player', kills=2) + add('vindicator-captain', type='minecraft:vindicator', captain=1, leader=1, killer='player', kills=2) + for animal in ['pig', 'strider', 'horse', 'camel', 'donkey']: + add(f'{animal}-saddle', type='minecraft:' + animal, saddle='minecraft:saddle', chance_saddle=2.0, killer='player', kills=2) + add(f'{animal}-saddle-default', type='minecraft:' + animal, saddle='minecraft:saddle', killer='player', kills=6) + add('zombie-horse', type='minecraft:zombie', vehicle='minecraft:zombie_horse', killer='player', kills=4) + add('zombie-baby-chicken', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', killer='player', kills=3) + add('zombie-baby-chicken-none', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', source='generic', kills=2) + add('husk-camel', type='minecraft:husk', vehicle='minecraft:camel_husk', killer='player', kills=3) + for weapon in WEAPONS: + add('wither-' + weapon.split(';')[-1].replace(':', ''), type='minecraft:wither', killer='player', weapon=weapon, kills=2) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-entity-death-loot-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + tables = resources / 'data/minecraft/loot_table/entities' + types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus(types) + inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + try: + matched = base.compare(build / 'server.txt', build / 'rust.txt') + except AssertionError as error: + raise SystemExit(str(error) + explain(build)) from None + base.ensure_sources_unchanged(sources, tested) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'types': len(types), 'skipped': sorted(SKIPPED), 'matched_output_lines': matched, 'sources_sha256': tested, + 'scope': 'LivingEntity.dropAllDeathLoot after the killer\'s killedEntity hook: entity loot tables under the world random ' + 'sequence, Mob.dropCustomDeathLoot equipment drops and durability, species death loot, experience orbs.'}) + print(f'{len(cases):,} death-drop cases over {len(types)} entity types match vanilla ({matched:,} lines)') + + +def explain(build): + def sections(path): + out, name = {}, None + for line in path.read_text(encoding='utf-8', errors='replace').splitlines(): + if line.startswith('== '): + name = line[3:] + out[name] = [] + elif name is not None: + out[name].append(line) + return out + left, right = sections(build / 'server.txt'), sections(build / 'rust.txt') + bad = [n for n in left if left[n] != right.get(n)] + report = f'\n{len(bad)} differing cases' + for name in bad[:30]: + a, b = left[name], right.get(name, []) + diffs = [(x, y) for x, y in zip(a, b) if x != y][:3] + if len(a) != len(b): + diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>')) + report += f'\n {name}: {diffs}' + return report + + +if __name__ == '__main__': + main()