Merge remote-tracking branch 'origin/parity/spawn-gear' into parity/save-roundtrip

This commit is contained in:
Ludovic Marie
2026-10-13 03:54:23 +02:00
12 changed files with 3399 additions and 44 deletions
+5 -6
View File
@@ -111,7 +111,7 @@ The client starts on the title screen. Command-line options (`--world`, `--seed`
## Project status
Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, spawned mob gear enchantments, the resource pack screen, a dedicated server mode, and worlds older than 1.17.
Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, the resource pack screen, a dedicated server mode, and worlds older than 1.17.
### Java parity: 89%
@@ -134,7 +134,7 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and
| Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included |
| World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla |
| Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded |
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing |
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases), spawned mobs' gear, enchantments and state (`finalizeSpawn`, 24,000 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain and villager breeding and gossip are missing |
| Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla |
| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), and the player list matches over 844,758 draw calls; the focused chat is not compared and player list heads use default skins |
| Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla |
@@ -154,10 +154,9 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and
### Roadmap
1. Finish the warden's brain and the sculk shrieker summoning it, and the tempted ghastling.
2. Villager breeding and gossip, and spawned mob gear enchantments (both started on their branches).
3. A dedicated server mode, and LAN hosting tested with a vanilla client.
4. Save upgrades from before 1.17, and the resource pack screen.
5. Platform-independent float math, so every harness also gives vanilla's results on macOS.
2. A dedicated server mode, and LAN hosting tested with a vanilla client.
3. Save upgrades from before 1.17, and the resource pack screen.
4. Platform-independent float math, so every harness also gives vanilla's results on macOS.
The rewrite is complete when it reaches one-to-one parity and packaged native builds pass the launch checks in [Rust rewrite status](docs/rust-parity.md#completion-criteria-and-playable-builds).
@@ -0,0 +1,531 @@
//! `Mob.finalizeSpawn` for differential tests against vanilla
//! (tools/test_finalize_spawn_parity.py): reads the cases of
//! `VanillaFinalizeSpawnOracle`, runs `mobs::finalize` with the same level
//! random and entity randoms, and prints every entity of the case in the
//! oracle's format.
//!
//! usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN
use horizon_client::{
assets::Assets,
blocks::BlockFacts,
enchant::Enchantments,
items::Items,
mobs::{
Mob, MobTypes, Species,
data::MobData,
finalize::{self, Attr, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries},
gear,
render::{DYE_NAMES, PROFESSIONS, VILLAGER_TYPES},
spawning::LocalDifficulty,
},
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use std::{collections::HashMap, fmt::Write as _, fs, path::Path, sync::Arc};
struct Level<'a> {
types: &'a MobTypes,
data: &'a MobData,
biome: String,
structure: Option<(String, [i32; 6])>,
phase: usize,
monsters: bool,
peaceful: bool,
time: i64,
halloween: bool,
roof: Option<i32>,
eseed: i64,
/// Every entity of the case in creation order (case chickens first).
created: usize,
/// The level's entities that can carry a zombie: (id, bounds, ridden).
chickens: Vec<(u32, Aabb, bool)>,
rides: Vec<(u32, u32)>,
}
impl FinalizeLevel for Level<'_> {
fn biome(&self, _pos: [i32; 3]) -> String {
self.biome.clone()
}
fn biome_tag(&self, tag: &str, _pos: [i32; 3]) -> bool {
self.data.biome_has(tag, &self.biome)
}
fn structures_with_piece_at(&self, pos: [i32; 3]) -> Vec<String> {
match &self.structure {
Some((id, b))
if pos[0] >= b[0]
&& pos[0] <= b[3]
&& pos[1] >= b[1]
&& pos[1] <= b[4]
&& pos[2] >= b[2]
&& pos[2] <= b[5] =>
{
vec![id.clone()]
}
_ => Vec::new(),
}
}
fn moon_phase(&self, _pos: [i32; 3]) -> usize {
self.phase
}
fn spawning_monsters(&self) -> bool {
self.monsters
}
fn no_collision(&self, bounds: Aabb) -> bool {
// A floor under the spawn point and an optional roof layer.
self.roof.is_none_or(|y| {
let (lo, hi) = (
bounds.min(horizon_core::geometry::Axis::Y),
bounds.max(horizon_core::geometry::Axis::Y),
);
!(lo < f64::from(y) + 1.0 && hi > f64::from(y))
})
}
fn free_chicken(&self, bounds: Aabb) -> Option<u32> {
self.chickens
.iter()
.find(|(_, b, ridden)| !ridden && b.intersects(bounds))
.map(|c| c.0)
}
fn ride_chicken(&mut self, chicken: u32, rider: u32) {
if let Some(c) = self.chickens.iter_mut().find(|c| c.0 == chicken) {
c.2 = true;
}
self.rides.push((chicken, rider));
}
fn game_time(&self) -> i64 {
self.time
}
fn halloween(&self) -> bool {
self.halloween
}
fn create(&mut self, kind: &str, _reason: Reason) -> Option<Mob> {
if self.peaceful && !finalize::allowed_in_peaceful(kind) {
return None;
}
let t = Arc::new(self.types.types.get(kind)?.clone());
let index = self.created;
self.created += 1;
let mut m = Mob::new(index as u32 + 1, t, Vec3::ZERO, 0.0);
m.random = LegacyRandom::new(self.eseed.wrapping_add(index as i64));
Some(m)
}
}
fn hex64(v: f64) -> String {
format!("{:x}", v.to_bits())
}
fn hex32(v: f32) -> String {
format!("{:x}", v.to_bits())
}
const HORSE: [&str; 7] = [
"white",
"creamy",
"chestnut",
"brown",
"black",
"gray",
"dark_brown",
];
const MARKINGS: [&str; 5] = ["none", "white", "white_field", "white_dots", "black_dots"];
const RABBITS: [&str; 6] = ["brown", "white", "black", "white_splotched", "gold", "salt"];
const PARROTS: [&str; 5] = ["red_blue", "blue", "green", "yellow_blue", "gray"];
const AXOLOTLS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
const SALMON: [&str; 3] = ["small", "medium", "large"];
const GENES: [&str; 7] = [
"normal",
"lazy",
"worried",
"playful",
"brown",
"weak",
"aggressive",
];
const MEMORIES: [&str; 7] = [
"long_jump_cooldown",
"ram_cooldown",
"attack_target_cooldown",
"hunted_recently",
"dig_cooldown",
"is_emerging",
"home",
];
fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec<String>) {
use Species as S;
let s = m.species();
let named = |reg: &finalize::VariantRegistry, i: u8| {
format!(
"minecraft:{}",
reg.names.get(i as usize).map_or("?", |n| n.as_str())
)
};
let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant));
match s {
S::Pig => {
v.push(var);
v.push(named(&regs.pig_sound, m.extra.sound_variant));
}
S::Cow => {
v.push(var);
v.push(named(&regs.cow_sound, m.extra.sound_variant));
}
S::Mooshroom => v.push(if m.extra.variant == 0 { "red" } else { "brown" }.into()),
S::Chicken => {
v.push(var);
v.push(named(&regs.chicken_sound, m.extra.sound_variant));
v.push(format!("jockey={}", m.extra.jockey));
}
S::Cat => {
v.push(var);
v.push(named(&regs.cat_sound, m.extra.sound_variant));
}
S::Wolf => {
v.push(var);
v.push(named(&regs.wolf_sound, m.extra.sound_variant));
}
S::Frog | S::ZombieNautilus => v.push(var),
S::Sheep => v.push(DYE_NAMES[m.extra.color as usize & 15].into()),
S::Horse => v.push(format!(
"{}/{}",
HORSE[m.extra.variant as usize % 7],
MARKINGS[m.extra.variant2 as usize % 5]
)),
S::Llama | S::TraderLlama => v.push(format!(
"{}/{}",
horizon_client::mobs::llama::VARIANTS[m.extra.variant as usize % 4],
m.extra.variant2
)),
S::SkeletonHorse => v.push(format!("trap={}", m.extra.trap)),
S::Fox => v.push(if m.extra.variant == 1 { "snow" } else { "red" }.into()),
S::Rabbit => v.push(RABBITS[m.extra.variant as usize % 6].into()),
S::Parrot => v.push(PARROTS[m.extra.variant as usize % 5].into()),
S::Axolotl => v.push(AXOLOTLS[m.extra.variant as usize % 5].into()),
S::TropicalFish => {
let p = u32::from(m.extra.variant);
let pattern = if p < 6 { p << 8 } else { 1 | (p - 6) << 8 };
let packed = (pattern & 0xFFFF)
| (u32::from(m.extra.variant2) & 0xFF) << 16
| (u32::from(m.extra.variant3) & 0xFF) << 24;
v.push((packed as i32).to_string());
}
S::Salmon => v.push(SALMON[m.extra.variant as usize % 3].into()),
S::Panda => v.push(format!(
"{}/{}",
GENES[m.extra.variant as usize % 7],
GENES[m.extra.variant2 as usize % 7]
)),
S::Goat => v.push(format!(
"scream={} horns={},{}",
m.extra.screaming, !m.extra.lost_horns[0], !m.extra.lost_horns[1]
)),
S::Slime | S::MagmaCube | S::SulfurCube => v.push(format!("size={}", m.extra.size.max(1))),
S::Villager => v.push(format!(
"minecraft:{}/minecraft:{}/{}",
VILLAGER_TYPES[m.extra.variant as usize % 7],
PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()],
m.extra.variant3.max(1)
)),
S::ZombieVillager => v.push(format!(
"minecraft:{}/{}",
VILLAGER_TYPES[m.extra.variant as usize % 7],
m.extra.variant3.max(1)
)),
S::Phantom => v.push(format!("size={}", m.extra.size)),
S::Turtle => v.push(format!(
"home={}",
m.extra
.home
.map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2]))
)),
S::Dolphin => v.push(format!("air={}", m.air)),
_ => {}
}
if matches!(
s,
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin
) {
v.push(format!("doors={}", m.extra.can_break_doors));
}
if horizon_client::mobs::raider::is_raider(s) {
let st = horizon_client::mobs::raider::state(m);
v.push(format!(
"leader={} patrolling={}",
st.is_some_and(|s| s.patrol_leader),
st.is_some_and(|s| s.patrolling)
));
v.push(format!("raid={}", st.is_some_and(|s| s.can_join_raid)));
}
if s == S::Strider {
v.push(format!("saddled={}", m.extra.saddled));
}
}
fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String {
let mut t = vec![m.kind.id.clone()];
let vehicle = m
.extra
.mount
.and_then(|v| all.iter().position(|o| o.id == v))
.map_or("-".to_owned(), |i| i.to_string());
t.push(format!("veh={vehicle}"));
if finalize::ageable(m.species()) {
t.push(format!("age={}", m.extra.age));
} else {
t.push(format!("baby={}", m.is_baby()));
}
t.push(format!("hp={}", hex32(m.health)));
t.push(format!("lh={}", m.extra.left_handed));
t.push(format!("loot={}", m.can_pick_up_loot()));
t.push(format!("persist={}", m.persistent));
let mut eq = Vec::new();
for (slot, name) in finalize::SLOT_NAMES.iter().enumerate() {
let Some(id) = finalize::item(m, slot) else {
continue;
};
let mut text = id.to_string();
let g = match slot {
0 => Some(gear::MAIN),
1 => Some(gear::OFF),
2 => Some(gear::FEET),
3 => Some(gear::LEGS),
4 => Some(gear::CHEST),
5 => Some(gear::HEAD),
_ => None,
};
if let (Some(g), Some(levels)) = (g, gear::gear(m)) {
let mut list: Vec<String> = levels.slots[g]
.iter()
.map(|(e, l)| format!("{e}={l}"))
.collect();
list.sort();
if !list.is_empty() {
let _ = write!(text, "[{}]", list.join(","));
}
}
if slot == 5 && horizon_client::mobs::raider::is_captain(m) {
text.push_str("*4");
}
eq.push(format!("{name}:{text}"));
}
t.push(format!(
"eq={}",
if eq.is_empty() {
"-".into()
} else {
eq.join(";")
}
));
let drops: Vec<String> = finalize::SLOT_NAMES
.iter()
.enumerate()
.filter_map(|(i, name)| {
let d = finalize::stored_drop_chance(m, i);
(d != 0.085).then(|| format!("{name}:{}", hex32(d)))
})
.collect();
t.push(format!(
"drop={}",
if drops.is_empty() {
"-".into()
} else {
drops.join(";")
}
));
let attrs: Vec<String> = [
Attr::MaxHealth,
Attr::MovementSpeed,
Attr::FollowRange,
Attr::AttackDamage,
Attr::KnockbackResistance,
Attr::SpawnReinforcements,
Attr::JumpStrength,
]
.into_iter()
.filter(|a| finalize::default_value(m, *a).is_some())
.map(|a| format!("{}:{}", a.name(), hex64(finalize::value(m, a))))
.collect();
t.push(format!("a={}", attrs.join(",")));
let mut fx: Vec<String> = m
.extra
.effects
.iter()
.map(|(e, d, a)| format!("{e}:{a}:{d}"))
.collect();
fx.sort();
t.push(format!(
"fx={}",
if fx.is_empty() {
"-".into()
} else {
fx.join(",")
}
));
let mem: Vec<String> = MEMORIES
.iter()
.filter_map(|name| {
let (_, value, ttl) = m.extra.memories.iter().find(|x| x.0 == *name)?;
let text = match *name {
"hunted_recently" => "true".to_owned(),
"dig_cooldown" | "is_emerging" => "INSTANCE".to_owned(),
"home" => m
.extra
.home
.map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2])),
_ => value.to_string(),
};
Some(format!("{name}:{text}:{ttl}"))
})
.collect();
if !mem.is_empty() {
t.push(format!("mem={}", mem.join(",")));
}
let mut v = Vec::new();
variant(m, regs, &mut v);
if !v.is_empty() {
t.push(format!("v={}", v.join(" ").replace(' ', "_")));
}
t.join(" ")
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let halloween = args.get(4).is_some_and(|h| h == "true");
let assets = Assets::load(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let mob_data = MobData::load(root, &facts);
let items = Items::tags_only(root)?;
let enchantments = Enchantments::load(root);
let types = MobTypes::load(root)?;
let registries = SpawnRegistries::load(root);
let camel = &types.types["minecraft:camel_husk"];
let data = SpawnData {
registries: &registries,
enchantments: &enchantments,
items: &items,
camel_husk_size: (camel.width as f32, camel.height as f32),
};
let mut out = format!("halloween {halloween}\n");
for line in input.lines().filter(|l| !l.trim().is_empty()) {
let mut c: HashMap<&str, &str> = HashMap::new();
let mut name = "";
for token in line.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 p: Vec<f64> = get("pos", "0,0,0")
.split(',')
.map(|x| x.parse().unwrap_or(0.0))
.collect();
let pos = Vec3::new(p[0], p[1], p[2]);
let block = [
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32,
];
let base = match get("difficulty", "normal").as_str() {
"peaceful" => 0,
"easy" => 1,
"hard" => 3,
_ => 2,
};
let phase: usize = get("phase", "0").parse().unwrap_or(0);
let time: i64 = get("time", "0").parse().unwrap_or(0);
let inhabited: i64 = get("inhabited", "0").parse().unwrap_or(0);
let difficulty = LocalDifficulty::new(
base,
time,
inhabited,
horizon_client::mobs::spawning::MOON_BRIGHTNESS[phase & 7],
);
let mut level = Level {
types: &types,
data: &mob_data,
biome: get("biome", "minecraft:plains"),
structure: c.get("structure").map(|s| {
(
(*s).to_owned(),
[
block[0] - 8,
block[1] - 8,
block[2] - 8,
block[0] + 8,
block[1] + 8,
block[2] + 8,
],
)
}),
phase,
monsters: get("monsters", "1") != "0",
peaceful: base == 0,
time,
halloween,
roof: c
.get("roof")
.and_then(|r| r.parse::<i32>().ok())
.map(|r| block[1] + r),
eseed: get("eseed", "0").parse().unwrap_or(0),
created: 0,
chickens: Vec::new(),
rides: Vec::new(),
};
let mut all: Vec<Mob> = Vec::new();
let chickens: usize = get("chickens", "0").parse().unwrap_or(0);
for i in 0..chickens {
if let Some(mut chicken) = level.create("minecraft:chicken", Reason::Load) {
chicken.position = Vec3::new(pos.x + i as f64, pos.y, pos.z);
level.chickens.push((chicken.id, chicken.bounds(), false));
all.push(chicken);
}
}
let kind = get("type", "minecraft:pig");
let reason = Reason::parse(&get("reason", "NATURAL")).unwrap_or(Reason::Natural);
let pack: usize = get("pack", "1").parse().unwrap_or(1);
let mut random = LegacyRandom::new(get("seed", "0").parse().unwrap_or(0));
let mut group = None;
for _ in 0..pack {
let Some(mut mob) = level.create(&kind, reason) else {
break;
};
mob.position = pos;
mob.previous = pos;
let mut cx = Ctx {
level: &mut level,
random: &mut random,
difficulty,
data: &data,
created: Vec::new(),
};
group = finalize::finalize(&mut cx, &mut mob, reason, group);
let created = std::mem::take(&mut cx.created);
all.push(mob);
all.extend(created);
}
for (chicken, rider) in std::mem::take(&mut level.rides) {
if let Some(c) = all.iter_mut().find(|m| m.id == chicken) {
c.extra.jockey = true;
c.extra.rider = Some(rider);
}
}
all.sort_by_key(|m| m.id);
let mut parts: Vec<String> = all.iter().map(|m| describe(m, &all, &registries)).collect();
for m in &mut all {
parts.push(format!("rng {}", m.random.next_long()));
}
parts.push(format!("next {}", random.next_long()));
let _ = writeln!(out, "{name} {}", parts.join(" | "));
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
+1 -1
View File
@@ -140,7 +140,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, value) in [
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))),
("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))),
("LeftHanded", Tag::Byte(0)),
(
"Brain",
@@ -144,6 +144,7 @@ pub(super) fn player_type(root: &Path) -> Option<Arc<MobType>> {
armor_toughness: 0.0,
knockback_resistance: 0.0,
jump_strength: 0.42,
attributes: Default::default(),
gravity: 0.08,
safe_fall_distance: 3.0,
fall_damage_multiplier: 1.0,
+70 -5
View File
@@ -25,6 +25,7 @@ pub mod drops;
pub mod enderman;
pub mod equine;
pub mod farm;
pub mod finalize;
pub mod gear;
pub mod goals;
pub mod golem;
@@ -205,6 +206,8 @@ pub struct MobType {
pub armor_toughness: f32,
pub knockback_resistance: f64,
pub jump_strength: f64,
/// Every default attribute value of the type (`entity-types.json`).
pub attributes: Arc<HashMap<String, f64>>,
pub gravity: f64,
pub safe_fall_distance: f64,
pub fall_damage_multiplier: f64,
@@ -238,12 +241,35 @@ impl MobType {
self.layers.get(key)
}
}
/// Each type's default attribute values, parsed exactly (serde_json's
/// default float parsing can miss the nearest double by one ulp).
fn exact_attributes(bytes: &[u8]) -> HashMap<String, HashMap<String, f64>> {
use serde_json::value::RawValue;
type Raw = HashMap<String, Box<RawValue>>;
let Ok(types) = serde_json::from_slice::<Raw>(bytes) else {
return HashMap::new();
};
types
.into_iter()
.filter_map(|(id, t)| {
let t: Raw = serde_json::from_str(t.get()).ok()?;
let attrs: Raw = serde_json::from_str(t.get("attributes")?.get()).ok()?;
let values = attrs
.into_iter()
.filter_map(|(k, v)| v.get().trim().parse::<f64>().ok().map(|v| (k, v)))
.collect();
Some((id, values))
})
.collect()
}
pub struct MobTypes {
pub types: HashMap<String, MobType>,
}
impl MobTypes {
pub fn load(root: &Path) -> crate::Result<Self> {
let types: Value = serde_json::from_slice(&fs::read(root.join("entity-types.json"))?)?;
let bytes = fs::read(root.join("entity-types.json"))?;
let types: Value = serde_json::from_slice(&bytes)?;
let exact = exact_attributes(&bytes);
let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json"))?)?;
let item_tags = crate::items::load_tags(root, "item").unwrap_or_default();
sulfur_cube::load_archetype_items(&item_tags);
@@ -268,7 +294,8 @@ impl MobTypes {
let Some(model) = models.get(&model_key) else {
continue;
};
let attr = |k: &str| t["attributes"][format!("minecraft:{k}")].as_f64();
let defaults = exact.get(&id).cloned().unwrap_or_default();
let attr = |k: &str| defaults.get(&format!("minecraft:{k}")).copied();
let mut layers = HashMap::new();
if let Some(all) = models.as_object() {
for prefix in def.layer_prefixes() {
@@ -302,6 +329,7 @@ impl MobTypes {
armor_toughness: attr("armor_toughness").unwrap_or(0.0) as f32,
knockback_resistance: attr("knockback_resistance").unwrap_or(0.0),
jump_strength: attr("jump_strength").unwrap_or(0.42),
attributes: Arc::new(defaults.clone()),
gravity: attr("gravity").unwrap_or(0.08),
safe_fall_distance: attr("safe_fall_distance").unwrap_or(3.0),
fall_damage_multiplier: attr("fall_damage_multiplier").unwrap_or(1.0),
@@ -461,6 +489,9 @@ pub struct Attrs {
pub attack_damage: f32,
pub max_health: f32,
pub follow_range: f64,
pub knockback_resistance: f64,
pub spawn_reinforcements: f64,
pub jump_strength: f64,
}
/// Species-specific persistent state (variants, colours, taming, ageing...).
#[derive(Clone, Debug, Default)]
@@ -561,6 +592,24 @@ pub struct Extra {
/// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set
/// explicitly; None uses the defaults of `drops::drop_chance`.
pub drop_chances: Option<Box<[f32; 8]>>,
/// `Mob.leftHanded`.
pub left_handed: bool,
/// The sound variant: index in the species' `*_sound_variant` registry.
pub sound_variant: u8,
/// `Zombie.canBreakDoors`.
pub can_break_doors: bool,
/// A goat's `IsScreamingGoat` and the horns it lost (left, right).
pub screaming: bool,
pub lost_horns: [bool; 2],
/// Attribute bases and permanent modifiers set by `finalizeSpawn`.
pub attributes: Option<Box<finalize::Attributes>>,
/// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry).
pub memories: Vec<(&'static str, i64, i64)>,
/// A camel's `LAST_POSE_CHANGE_TICK`.
pub pose_change_tick: i64,
/// The school leader a fish follows, and a tropical fish that swims alone.
pub leader: Option<u32>,
pub lone: bool,
/// A breeze's or creaking's brain (`monster_brain`).
pub brain: Option<Box<monster_brain::Brain>>,
}
@@ -1215,17 +1264,24 @@ impl Mob {
attack_damage: kind.attack_damage,
max_health: kind.max_health,
follow_range: kind.follow_range,
knockback_resistance: kind.knockback_resistance,
spawn_reinforcements: kind
.attributes
.get("minecraft:spawn_reinforcements")
.copied()
.unwrap_or(0.0),
jump_strength: kind.jump_strength,
},
kind,
};
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay,
// Dolphin, Fox and Panda constructors.
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Dolphin,
// Fox and Panda constructors (an allay's is false until it holds
// something: it overrides canPickUpLoot).
mob.extra.pick_up_loot = matches!(
mob.species(),
Species::Villager
| Species::Piglin
| Species::PiglinBrute
| Species::Allay
| Species::Dolphin
| Species::Fox
| Species::Panda
@@ -1233,6 +1289,15 @@ impl Mob {
ai::register(&mut mob);
mob
}
/// `Mob.canPickUpLoot`, with the overrides: an allay that holds
/// something off its pickup cooldown, a sulfur cube with no block.
pub fn can_pick_up_loot(&self) -> bool {
match self.species() {
Species::Allay => self.extra.main_hand.is_some() && self.extra.ints[3] <= 0,
Species::SulfurCube => !sulfur_cube::has_body(self),
_ => self.extra.pick_up_loot,
}
}
pub fn bounds(&self) -> Aabb {
let w = f64::from(self.width()) / 2.0;
Aabb::new(
+7 -4
View File
@@ -895,11 +895,14 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|| super::nautilus::is_nautilus(m.species()) && m.extra.tame
|| m.species() == Species::SulfurCube
&& (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0);
// removeWhenFarAway: animals, wardens, patrols and raiders, zombie
// villagers being cured and ridden mobs stay.
// removeWhenFarAway: animals, wardens, allays, patrols and raiders,
// zombie villagers being cured and ridden mobs stay; the wither's
// checkDespawn never removes it for distance.
let creature = m.kind.category == "creature";
let removable = !(m.species() == Species::Warden
|| creature && m.kind.flags.animal && !m.extra.jockey
let removable = !(matches!(
m.species(),
Species::Warden | Species::Allay | Species::Wither
) || creature && m.kind.flags.animal && !m.extra.jockey
|| super::raider::keeps_alive(m, d)
|| super::zombie_villager::keeps_alive(m)
|| super::riders::keeps_alive(m));
-1
View File
@@ -27,7 +27,6 @@ pub fn register(m: &mut Mob) {
m.ai.nav.kind = NavKind::Flying;
// FlyingPathNavigation.setRequiredPathLength(48).
m.ai.nav.required_path_length = 48.0;
m.persistent = true;
let g = &mut m.ai.goals;
g.add(0, Panic::new(2.5));
g.add(1, Fetch);
+29 -26
View File
@@ -445,35 +445,38 @@ impl Goal for PufferfishPuff {
}
}
/// finalizeSpawn variants (tropical fish patterns and colours).
/// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
pub const COMMON_TROPICAL: [(u8, u8, u8); 22] = [
(7, 1, 7),
(6, 7, 7),
(6, 7, 11),
(11, 0, 7),
(1, 11, 7),
(0, 1, 0),
(5, 6, 3),
(9, 10, 4),
(11, 0, 14),
(5, 0, 4),
(8, 0, 7),
(11, 0, 1),
(3, 9, 6),
(4, 5, 3),
(10, 14, 0),
(2, 7, 14),
(9, 14, 0),
(6, 0, 4),
(0, 14, 0),
(1, 7, 0),
(3, 9, 4),
(6, 4, 4),
];
pub fn finalize(m: &mut Mob) {
if m.species() == Species::TropicalFish {
// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
const COMMON: [(u8, u8, u8); 22] = [
(7, 1, 7),
(6, 7, 7),
(6, 7, 11),
(11, 0, 7),
(1, 11, 7),
(0, 1, 0),
(5, 6, 3),
(9, 10, 4),
(11, 0, 14),
(5, 0, 4),
(8, 0, 7),
(11, 0, 1),
(3, 9, 6),
(4, 5, 3),
(10, 14, 0),
(2, 7, 14),
(9, 14, 0),
(6, 0, 4),
(0, 14, 0),
(1, 7, 0),
(3, 9, 4),
(6, 4, 4),
];
let (p, b, c) = if m.random.next_float() < 0.9 {
COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize]
COMMON_TROPICAL[m
.random
.next_int_bound(COMMON_TROPICAL.len() as i32)
.unwrap_or(0) as usize]
} else {
(
m.random.next_int_bound(12).unwrap_or(0) as u8,
File diff suppressed because it is too large Load Diff
-1
View File
@@ -28,7 +28,6 @@ pub fn register(m: &mut Mob) {
hovers: false,
};
m.ai.nav.kind = NavKind::Flying;
m.persistent = true;
let g = &mut m.ai.goals;
g.add(0, DoNothing);
g.add(
@@ -0,0 +1,527 @@
package dev.horizonlab.parity;
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.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.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.RandomSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.Brain;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.ItemEnchantments;
import net.minecraft.world.level.*;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.border.WorldBorder;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
/**
* Original oracle: Mob.finalizeSpawn as vanilla runs it, for every mob type,
* spawn reason, difficulty and local difficulty, on a stand-in ServerLevel
* (one biome, an optional structure piece, a floor and an optional roof,
* chickens standing by, the moon phase).
*
* Each case seeds the level random (what finalizeSpawn reads through
* level.getRandom()) and the entities' own randoms: every entity created
* in the case, the case's mobs and the jockeys finalizeSpawn makes, gets
* a LegacyRandomSource seeded eseed + its creation index, swapped in
* through each EntityType's factory. A pack of mobs is finalized in turn
* with the group data passed along, as NaturalSpawner does, each added to
* the level with its passengers.
*
* The log lists every entity of the case in creation order (equipment and
* enchantments, drop chances, CanPickUpLoot, LeftHanded, persistence, age,
* health, attribute values, effects, the species' variant state and spawn
* memories, its vehicle) and the next draws of the level random and of each
* entity's random, which pin every draw in between.
*/
public final class VanillaFinalizeSpawnOracle {
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);
putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value);
}
static Object get(Object target, Class<?> owner, String field) {
try {
Field f = owner.getDeclaredField(field);
f.setAccessible(true);
return f.get(target);
} catch (Exception e) { throw new RuntimeException(e); }
}
static final class Lvl extends ServerLevel {
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
RegistryAccess registries;
net.minecraft.server.MinecraftServer fake;
BlockState floor;
int floorY, roofY;
Holder<Biome> biome;
Difficulty difficulty;
DimensionType dimensionType;
ResourceKey<Level> dimensionKey;
List<Entity> entities = new ArrayList<>();
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
BiomeManager biomeManager;
WorldBorder border = new WorldBorder();
GameRules rules;
Structures structures;
RandomSource levelRandom;
long time;
int next = 1;
@Override public net.minecraft.server.MinecraftServer getServer() { return fake; }
@Override public RegistryAccess registryAccess() { return registries; }
@Override public Difficulty getDifficulty() { return difficulty; }
@Override public long getGameTime() { return time; }
@Override public int getNextEntityId() { return next++; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
@Override public BlockState getBlockState(BlockPos pos) {
if (pos.getY() == floorY) return floor;
if (pos.getY() == roofY) return Blocks.STONE.defaultBlockState();
return Blocks.AIR.defaultBlockState();
}
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
@Override public DimensionType dimensionType() { return dimensionType; }
@Override public ResourceKey<Level> dimension() { return dimensionKey; }
@Override public Holder<Biome> getBiome(BlockPos pos) { return biome; }
@Override public BiomeManager getBiomeManager() { return biomeManager; }
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
@Override public WorldBorder getWorldBorder() { return border; }
@Override public GameRules getGameRules() { return rules; }
@Override public RandomSource getRandom() { return levelRandom; }
@Override public int getSeaLevel() { return 63; }
net.minecraft.server.ServerScoreboard scoreboard;
@Override public net.minecraft.server.ServerScoreboard getScoreboard() { return scoreboard; }
@Override public net.minecraft.world.level.StructureManager structureManager() { return structures; }
@Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; }
@Override public boolean isSpawningMonsters() { return rules.get(GameRules.SPAWN_MOBS) && rules.get(GameRules.SPAWN_MONSTERS); }
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, double x, double y, double z, Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {}
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, net.minecraft.world.entity.Entity sourceEntity, Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {}
@Override public void gameEvent(Holder<net.minecraft.world.level.gameevent.GameEvent> gameEvent, Vec3 position, net.minecraft.world.level.gameevent.GameEvent.Context context) {}
@Override public void broadcastEntityEvent(Entity entity, byte event) {}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public List players() { return List.of(); }
@Override public Iterable<Entity> getAllEntities() { return entities; }
@Override public List<Entity> getEntities(Entity except, AABB bb, Predicate<? super Entity> selector) {
List<Entity> out = new ArrayList<>();
for (Entity e : entities) if (e != except && e.getBoundingBox().intersects(bb) && selector.test(e)) out.add(e);
return out;
}
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) {
List<T> out = new ArrayList<>();
for (Entity e : entities) {
T t = type.tryCast(e);
if (t != null && e.getBoundingBox().intersects(bb) && selector.test(t)) out.add(t);
}
return out;
}
@Override public boolean addFreshEntity(Entity entity) { if (!entities.contains(entity)) entities.add(entity); return true; }
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) { return null; }
}
/** One structure start whose single piece covers a box around the spawn point. */
static final class Structures extends net.minecraft.world.level.StructureManager {
Structures() { super(null, null, null); }
Lvl level;
Structure structure;
StructureStart start;
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Predicate<Structure> matcher) {
return start != null && matcher.test(structure) ? List.of(start) : List.of();
}
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Structure s) {
return start != null && s == structure ? List.of(start) : List.of();
}
@Override public RegistryAccess registryAccess() { return level.registries; }
}
static final class Piece extends StructurePiece {
Piece(BoundingBox box) { super(null, 0, box); }
@Override protected void addAdditionalSaveData(net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext context, net.minecraft.nbt.CompoundTag tag) {}
@Override public void postProcess(WorldGenLevel level, net.minecraft.world.level.StructureManager structureManager, net.minecraft.world.level.chunk.ChunkGenerator generator, RandomSource random,
BoundingBox chunkBB, ChunkPos chunkPos, BlockPos referencePos) {}
}
/** Entities created in the current case, and the seed base of their randoms. */
static List<Entity> created = new ArrayList<>();
static long entitySeed;
static boolean seeding;
static int otherIds;
@SuppressWarnings({"unchecked", "rawtypes"})
static void wrapFactories() throws Exception {
Field factory = EntityType.class.getDeclaredField("factory");
long offset = (long) objectFieldOffset.invoke(unsafe, factory);
factory.setAccessible(true);
for (EntityType<?> type : BuiltInRegistries.ENTITY_TYPE) {
EntityType.EntityFactory original = (EntityType.EntityFactory) factory.get(type);
EntityType.EntityFactory wrapped = (t, level) -> {
Entity e = original.create(t, level);
if (e != null && !seeding) e.setId(1000000 + otherIds++);
if (e != null && seeding) {
try {
put(e, Entity.class, "random", RandomSource.create(entitySeed + created.size()));
} catch (Exception ex) { throw new RuntimeException(ex); }
created.add(e);
e.setId(created.size());
}
return e;
};
putObject.invoke(unsafe, type, offset, wrapped);
}
}
static String hex(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
static String hex(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
static String id(Holder<?> h) { return h.unwrapKey().map(k -> k.identifier().toString()).orElse("?"); }
static final EquipmentSlot[] SLOTS = {EquipmentSlot.MAINHAND, EquipmentSlot.OFFHAND, EquipmentSlot.FEET, EquipmentSlot.LEGS,
EquipmentSlot.CHEST, EquipmentSlot.HEAD, EquipmentSlot.BODY, EquipmentSlot.SADDLE};
static String stack(ItemStack s) {
StringBuilder b = new StringBuilder(BuiltInRegistries.ITEM.getKey(s.getItem()).toString());
if (s.getCount() != 1) b.append('x').append(s.getCount());
ItemEnchantments e = s.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY);
if (!e.isEmpty()) {
List<String> list = new ArrayList<>();
for (var entry : e.entrySet()) list.add(id(entry.getKey()) + "=" + entry.getIntValue());
list.sort(null);
b.append('[').append(String.join(",", list)).append(']');
}
// Components besides enchantments (the ominous banner's).
int other = s.getComponentsPatch().forget(t -> t == DataComponents.ENCHANTMENTS).size();
if (other > 0) b.append('*').append(other);
return b.toString();
}
/** Loaded after the bootstrap. */
static final class Lists {
static final List<Map.Entry<String, Holder<Attribute>>> ATTRIBUTES = List.of(
Map.entry("max_health", Attributes.MAX_HEALTH), Map.entry("movement_speed", Attributes.MOVEMENT_SPEED),
Map.entry("follow_range", Attributes.FOLLOW_RANGE), Map.entry("attack_damage", Attributes.ATTACK_DAMAGE),
Map.entry("knockback_resistance", Attributes.KNOCKBACK_RESISTANCE), Map.entry("spawn_reinforcements", Attributes.SPAWN_REINFORCEMENTS_CHANCE),
Map.entry("jump_strength", Attributes.JUMP_STRENGTH));
static final List<Map.Entry<String, MemoryModuleType<?>>> MEMORIES = List.of(
Map.entry("long_jump_cooldown", MemoryModuleType.LONG_JUMP_COOLDOWN_TICKS), Map.entry("ram_cooldown", MemoryModuleType.RAM_COOLDOWN_TICKS),
Map.entry("attack_target_cooldown", MemoryModuleType.ATTACK_TARGET_COOLDOWN), Map.entry("hunted_recently", MemoryModuleType.HUNTED_RECENTLY),
Map.entry("dig_cooldown", MemoryModuleType.DIG_COOLDOWN), Map.entry("is_emerging", MemoryModuleType.IS_EMERGING),
Map.entry("home", MemoryModuleType.HOME));
}
/** The species state finalizeSpawn sets. */
static void variant(Entity e, List<String> v) {
if (e instanceof net.minecraft.world.entity.animal.pig.Pig p) {
v.add(id(p.getVariant()));
v.add(id((Holder<?>) data(p, p.getClass(), "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.cow.Cow c) {
v.add(id(c.getVariant()));
v.add(id((Holder<?>) data(c, net.minecraft.world.entity.animal.cow.Cow.class, "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.cow.MushroomCow m) {
v.add(m.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.chicken.Chicken c) {
v.add(id(c.getVariant()));
v.add(id((Holder<?>) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID")));
v.add("jockey=" + c.isChickenJockey());
} else if (e instanceof net.minecraft.world.entity.animal.feline.Cat c) {
v.add(id(c.getVariant()));
v.add(id((Holder<?>) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.wolf.Wolf w) {
v.add(id((Holder<?>) call(w, net.minecraft.world.entity.animal.wolf.Wolf.class, "getVariant")));
v.add(id((Holder<?>) data(w, w.getClass(), "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.frog.Frog f) {
v.add(id(f.getVariant()));
} else if (e instanceof net.minecraft.world.entity.animal.nautilus.ZombieNautilus n) {
v.add(id(n.getVariant()));
} else if (e instanceof net.minecraft.world.entity.animal.sheep.Sheep s) {
v.add(s.getColor().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.equine.Horse h) {
v.add(h.getVariant().getSerializedName() + "/" + h.getMarkings().name().toLowerCase(Locale.ROOT));
} else if (e instanceof net.minecraft.world.entity.animal.equine.Llama l) {
v.add(l.getVariant().getSerializedName() + "/" + l.getStrength());
} else if (e instanceof net.minecraft.world.entity.animal.equine.SkeletonHorse h) {
v.add("trap=" + h.isTrap());
} else if (e instanceof net.minecraft.world.entity.animal.fox.Fox f) {
v.add(f.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.rabbit.Rabbit r) {
v.add(r.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.parrot.Parrot p) {
v.add(p.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.axolotl.Axolotl a) {
v.add(a.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.fish.TropicalFish f) {
v.add(String.valueOf(call(f, net.minecraft.world.entity.animal.fish.TropicalFish.class, "getPackedVariant")));
} else if (e instanceof net.minecraft.world.entity.animal.fish.Salmon s) {
v.add(s.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.panda.Panda p) {
v.add(p.getMainGene().getSerializedName() + "/" + p.getHiddenGene().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.goat.Goat g) {
v.add("scream=" + g.isScreamingGoat() + " horns=" + g.hasLeftHorn() + "," + g.hasRightHorn());
} else if (e instanceof net.minecraft.world.entity.monster.cubemob.AbstractCubeMob s) {
v.add("size=" + s.getSize());
} else if (e instanceof net.minecraft.world.entity.npc.villager.Villager vi) {
v.add(id(vi.getVillagerData().type()) + "/" + id(vi.getVillagerData().profession()) + "/" + vi.getVillagerData().level());
} else if (e instanceof net.minecraft.world.entity.monster.zombie.ZombieVillager z) {
// The profession comes from the constructor's unseeded random.
v.add(id(z.getVillagerData().type()) + "/" + z.getVillagerData().level());
} else if (e instanceof net.minecraft.world.entity.monster.Phantom p) {
v.add("size=" + p.getPhantomSize());
} else if (e instanceof net.minecraft.world.entity.animal.turtle.Turtle t) {
BlockPos h = (BlockPos) get(t, net.minecraft.world.entity.animal.turtle.Turtle.class, "homePos");
v.add("home=" + (h == null ? "-" : h.getX() + "," + h.getY() + "," + h.getZ()));
} else if (e instanceof net.minecraft.world.entity.animal.dolphin.Dolphin d) {
v.add("air=" + d.getAirSupply());
}
if (e instanceof net.minecraft.world.entity.monster.zombie.Zombie z) v.add("doors=" + z.canBreakDoors());
if (e instanceof net.minecraft.world.entity.monster.PatrollingMonster p) v.add("leader=" + p.isPatrolLeader() + " patrolling=" + call(p, net.minecraft.world.entity.monster.PatrollingMonster.class, "isPatrolling"));
if (e instanceof net.minecraft.world.entity.raid.Raider r) v.add("raid=" + r.canJoinRaid());
if (e instanceof net.minecraft.world.entity.monster.Strider s) v.add("saddled=" + s.isSaddled());
}
@SuppressWarnings({"unchecked", "rawtypes"})
static Object data(Entity e, Class<?> owner, String name) {
return e.getEntityData().get((net.minecraft.network.syncher.EntityDataAccessor) fieldValue(owner, name));
}
static Object call(Object target, Class<?> owner, String name) {
try {
Method m = owner.getDeclaredMethod(name);
m.setAccessible(true);
return m.invoke(target);
} catch (Exception ex) { throw new RuntimeException(ex); }
}
static Object fieldValue(Class<?> owner, String name) {
try {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
return f.get(null);
} catch (Exception ex) { throw new RuntimeException(ex); }
}
static String describe(Entity e, List<Entity> all) {
List<String> t = new ArrayList<>();
t.add(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()).toString());
Entity vehicle = e.getVehicle();
t.add("veh=" + (vehicle == null ? "-" : Integer.toString(all.indexOf(vehicle))));
if (e instanceof AgeableMob a) t.add("age=" + a.getAge());
else if (e instanceof LivingEntity l) t.add("baby=" + l.isBaby());
if (e instanceof LivingEntity l) t.add("hp=" + hex(l.getHealth()));
if (e instanceof Mob m) {
t.add("lh=" + m.isLeftHanded());
t.add("loot=" + m.canPickUpLoot());
t.add("persist=" + m.isPersistenceRequired());
List<String> eq = new ArrayList<>();
for (EquipmentSlot s : SLOTS) {
ItemStack st = m.getItemBySlot(s);
if (!st.isEmpty()) eq.add(s.getSerializedName() + ":" + stack(st));
}
t.add("eq=" + (eq.isEmpty() ? "-" : String.join(";", eq)));
List<String> drops = new ArrayList<>();
for (EquipmentSlot s : SLOTS) {
float d = m.getDropChances().byEquipment(s);
if (d != 0.085F) drops.add(s.getSerializedName() + ":" + hex(d));
}
t.add("drop=" + (drops.isEmpty() ? "-" : String.join(";", drops)));
}
if (e instanceof LivingEntity l) {
List<String> attrs = new ArrayList<>();
for (var a : Lists.ATTRIBUTES) {
AttributeInstance inst = l.getAttribute(a.getValue());
if (inst != null) attrs.add(a.getKey() + ":" + hex(inst.getValue()));
}
t.add("a=" + String.join(",", attrs));
List<String> fx = new ArrayList<>();
for (MobEffectInstance i : l.getActiveEffects()) fx.add(id(i.getEffect()) + ":" + i.getAmplifier() + ":" + i.getDuration());
fx.sort(null);
t.add("fx=" + (fx.isEmpty() ? "-" : String.join(",", fx)));
Brain<?> brain = l.getBrain();
List<String> mem = new ArrayList<>();
for (var m : Lists.MEMORIES) {
if (!brain.hasMemoryValue(m.getValue())) continue;
Object value = brain.getMemory(m.getValue()).orElse(null);
String text = value instanceof GlobalPos g ? g.pos().getX() + "," + g.pos().getY() + "," + g.pos().getZ() : String.valueOf(value);
mem.add(m.getKey() + ":" + text + ":" + brain.getTimeUntilExpiry(m.getValue()));
}
if (!mem.isEmpty()) t.add("mem=" + String.join(",", mem));
}
List<String> v = new ArrayList<>();
variant(e, v);
if (!v.isEmpty()) t.add("v=" + String.join(" ", v).replace(' ', '_'));
return String.join(" ", t);
}
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 = net.minecraft.server.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();
var biomes = access.lookupOrThrow(Registries.BIOME);
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
var blockLookup = access.lookupOrThrow(Registries.BLOCK);
var structureLookup = access.lookupOrThrow(Registries.STRUCTURE);
var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
Lvl level = (Lvl) alloc(Lvl.class);
level.fake = server;
put(level, ServerLevel.class, "server", server);
level.registries = access;
// Level.playSound draws a sound seed before the (ignored) seeded sound.
put(level, net.minecraft.world.level.Level.class, "soundSeedGenerator", RandomSource.create(0L));
level.entities = new ArrayList<>();
level.scoreboard = new net.minecraft.server.ServerScoreboard(server);
level.border = new WorldBorder();
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) {
@Override public Holder<Biome> getBiome(BlockPos pos) { return level.biome; }
@Override public Holder<Biome> getBiome(int x, int y, int z) { return level.biome; }
};
Structures structures = (Structures) alloc(Structures.class);
structures.level = level;
level.structures = structures;
wrapFactories();
List<String> lines = Files.readAllLines(Path.of(args[0]));
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
w.println("halloween " + net.minecraft.util.SpecialDates.isHalloween());
for (String raw : lines) {
if (raw.isBlank()) continue;
Map<String, String> c = new LinkedHashMap<>();
for (String token : raw.trim().split("\\s+")) {
int eq = token.indexOf('=');
if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1));
}
try {
level.dimensionKey = ResourceKey.create(Registries.DIMENSION, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")));
level.dimensionType = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, level.dimensionKey.identifier())).value();
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
level.time = Long.parseLong(c.getOrDefault("time", "0"));
level.rules.set(GameRules.SPAWN_MONSTERS, !c.getOrDefault("monsters", "1").equals("0"), null);
int phase = Integer.parseInt(c.getOrDefault("phase", "0"));
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level)
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
.set(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, MoonPhase.values()[phase]).build())
.build();
String[] p = c.get("pos").split(",");
double x = Double.parseDouble(p[0]), y = Double.parseDouble(p[1]), z = Double.parseDouble(p[2]);
BlockPos block = BlockPos.containing(x, y, z);
level.floorY = block.getY() - 1;
level.floor = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, c.getOrDefault("floor", "minecraft:grass_block"), false).blockState();
level.roofY = c.containsKey("roof") ? block.getY() + Integer.parseInt(c.get("roof")) : Integer.MIN_VALUE;
structures.start = null;
if (c.containsKey("structure")) {
structures.structure = structureLookup.getValue(Identifier.parse(c.get("structure")));
BoundingBox box = new BoundingBox(block.getX() - 8, block.getY() - 8, block.getZ() - 8, block.getX() + 8, block.getY() + 8, block.getZ() + 8);
structures.start = new StructureStart(structures.structure, new ChunkPos(block.getX() >> 4, block.getZ() >> 4), 0,
new PiecesContainer(List.of(new Piece(box))));
}
level.entities.clear();
level.levelRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
put(level, Level.class, "random", level.levelRandom);
created = new ArrayList<>();
entitySeed = Long.parseLong(c.getOrDefault("eseed", "0"));
seeding = true;
// Chickens already standing by (zombie jockeys look for one).
int chickens = Integer.parseInt(c.getOrDefault("chickens", "0"));
for (int i = 0; i < chickens; i++) {
Entity chicken = EntityTypes.CHICKEN.create(level, EntitySpawnReason.LOAD);
chicken.setPos(x + i, y, z);
level.entities.add(chicken);
}
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type")));
EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "NATURAL"));
float moon = DimensionType.MOON_BRIGHTNESS_PER_PHASE[phase];
DifficultyInstance difficulty = new DifficultyInstance(level.difficulty, level.time, Long.parseLong(c.getOrDefault("inhabited", "0")), moon);
int pack = Integer.parseInt(c.getOrDefault("pack", "1"));
SpawnGroupData group = null;
for (int i = 0; i < pack; i++) {
Entity e = type.create(level, reason);
if (e == null) break; // monsters do not exist in peaceful
if (!(e instanceof Mob mob)) throw new IllegalStateException("not a mob");
mob.snapTo(x, y, z, 0.0F, 0.0F);
group = mob.finalizeSpawn(level, difficulty, reason, group);
level.addFreshEntityWithPassengers(mob);
}
seeding = false;
List<String> out = new ArrayList<>();
for (Entity e : created) out.add(describe(e, created));
for (Entity e : created) out.add("rng " + e.getRandom().nextLong());
out.add("next " + level.levelRandom.nextLong());
w.println(c.get("name") + " " + String.join(" | ", out));
} catch (Throwable t) {
seeding = false;
Throwable cause = t;
while ((cause instanceof InvocationTargetException || cause instanceof RuntimeException && cause.getCause() != null) && cause.getCause() != null) cause = cause.getCause();
StringBuilder line = new StringBuilder(c.get("name") + " error " + cause);
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame);
w.println(line);
}
}
}
System.exit(0);
}
}
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Compare Mob.finalizeSpawn (spawned mob gear, enchantments and state) with vanilla.
Java (VanillaFinalizeSpawnOracle) creates each case's mobs on a stand-in
ServerLevel and runs vanilla's finalizeSpawn with a seeded level random (what
finalizeSpawn reads through level.getRandom()) and seeded entity randoms; Rust
(finalize_spawn_fixture) runs horizon_client::mobs::finalize on the same case.
Cases cover every mob type, every spawn reason, peaceful to hard, game times,
inhabited times and moon phases (the local difficulty and its special
multiplier), packs sharing group data, biomes (variants, villager types,
sheep colours, rabbit and fox types), structures (black cats), roofs (camel
husk room) and chickens standing by (zombie jockeys).
Each entity created in a case, the mobs and the jockeys finalizeSpawn makes,
is compared: equipment with its enchantments, drop chances, CanPickUpLoot,
LeftHanded, persistence, age, health, attribute values, effects, variants,
the memories finalizeSpawn sets and the vehicle it rides; then the next draw
of every entity random and of the level random, which pins every draw in
between.
"""
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
REASONS = ['NATURAL', 'CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'BREEDING', 'MOB_SUMMONED', 'JOCKEY', 'EVENT',
'CONVERSION', 'REINFORCEMENT', 'TRIGGERED', 'BUCKET', 'SPAWN_ITEM_USE', 'COMMAND', 'DISPENSER', 'PATROL',
'TRIAL_SPAWNER', 'LOAD', 'DIMENSION_TRAVEL']
# Mobs whose finalizeSpawn draws, by how often the corpus picks them.
GEARED = ['zombie', 'husk', 'drowned', 'zombie_villager', 'zombified_piglin', 'skeleton', 'stray', 'bogged', 'parched',
'wither_skeleton', 'pillager', 'vindicator', 'piglin', 'piglin_brute', 'vex', 'fox', 'spider', 'illusioner',
'evoker', 'ravager', 'witch']
OTHERS = ['pig', 'cow', 'mooshroom', 'sheep', 'chicken', 'rabbit', 'horse', 'donkey', 'mule', 'llama', 'trader_llama',
'goat', 'panda', 'polar_bear', 'wolf', 'cat', 'ocelot', 'parrot', 'bee', 'turtle', 'armadillo', 'frog',
'axolotl', 'squid', 'glow_squid', 'cod', 'salmon', 'tropical_fish', 'pufferfish', 'dolphin', 'bat', 'villager',
'wandering_trader', 'iron_golem', 'snow_golem', 'creeper', 'cave_spider', 'enderman', 'endermite',
'silverfish', 'slime', 'magma_cube', 'phantom', 'hoglin', 'zoglin', 'ghast', 'blaze', 'strider', 'guardian',
'elder_guardian', 'shulker', 'camel', 'allay', 'breeze', 'sniffer', 'happy_ghast', 'warden', 'creaking',
'camel_husk', 'nautilus', 'zombie_nautilus', 'sulfur_cube', 'zombie_horse', 'skeleton_horse', 'tadpole',
'giant', 'wither']
BIOMES = ['minecraft:plains', 'minecraft:desert', 'minecraft:snowy_plains', 'minecraft:snowy_taiga', 'minecraft:taiga',
'minecraft:jungle', 'minecraft:bamboo_jungle', 'minecraft:swamp', 'minecraft:mangrove_swamp',
'minecraft:savanna', 'minecraft:badlands', 'minecraft:forest', 'minecraft:grove', 'minecraft:old_growth_pine_taiga',
'minecraft:old_growth_spruce_taiga', 'minecraft:sparse_jungle', 'minecraft:windswept_savanna',
'minecraft:mushroom_fields', 'minecraft:river', 'minecraft:frozen_river', 'minecraft:ocean',
'minecraft:warm_ocean', 'minecraft:lukewarm_ocean', 'minecraft:cold_ocean', 'minecraft:frozen_ocean',
'minecraft:ice_spikes', 'minecraft:cherry_grove', 'minecraft:pale_garden', 'minecraft:dripstone_caves',
'minecraft:lush_caves', 'minecraft:deep_dark', 'minecraft:nether_wastes', 'minecraft:crimson_forest',
'minecraft:soul_sand_valley', 'minecraft:the_end', 'minecraft:snowy_slopes', 'minecraft:frozen_peaks',
'minecraft:wooded_badlands', 'minecraft:beach', 'minecraft:snowy_beach', 'minecraft:meadow',
'minecraft:sulfur_caves']
STRUCTURES = ['minecraft:swamp_hut', 'minecraft:village_plains', 'minecraft:pillager_outpost', 'minecraft:fortress',
'minecraft:trial_chambers']
FLOORS = ['minecraft:grass_block', 'minecraft:sand', 'minecraft:stone', 'minecraft:snow_block', 'minecraft:netherrack']
def dimension(biome):
if biome in ('minecraft:nether_wastes', 'minecraft:crimson_forest', 'minecraft:soul_sand_valley'):
return 'minecraft:the_nether'
if biome == 'minecraft:the_end':
return 'minecraft:the_end'
return 'minecraft:overworld'
def corpus():
rng = random.Random(0x46494E414C)
cases = []
for k in range(int(os.environ.get('FINALIZE_SPAWN_CASES', '24000'))):
kind = rng.choice(GEARED) if rng.random() < 0.55 else rng.choice(OTHERS)
reason = rng.choice(['NATURAL'] * 10 + ['CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'COMMAND', 'SPAWN_ITEM_USE',
'TRIAL_SPAWNER', 'PATROL', 'EVENT', 'JOCKEY'] * 2 + REASONS)
biome = rng.choice(BIOMES)
kv = {
'type': f'minecraft:{kind}',
'reason': reason,
'difficulty': rng.choice(['hard', 'hard', 'normal', 'normal', 'easy', 'peaceful']),
'time': rng.choice([0, 0, 50000, 72000, 400000, 800000, 1512000, 3000000, rng.randrange(0, 4000000)]),
'inhabited': rng.choice([0, 0, 0, 100000, 1000000, 3600000, 5000000, rng.randrange(0, 4000000)]),
'phase': rng.randrange(8),
'seed': rng.randrange(-2**63, 2**63),
'eseed': rng.randrange(-2**47, 2**47),
'pack': rng.choice([1, 1, 1, 2, 3, 4, 6]),
'pos': f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.25, 0.0]):.2f},{rng.randrange(-30, 120)},'
f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.75, 0.0]):.2f}',
'biome': biome,
'dim': dimension(biome),
'floor': rng.choice(FLOORS),
}
if rng.random() < 0.15:
kv['structure'] = rng.choice(STRUCTURES)
if rng.random() < 0.2:
kv['roof'] = rng.choice([1, 2, 3])
if rng.random() < 0.15:
kv['chickens'] = rng.choice([1, 2])
if rng.random() < 0.05:
kv['monsters'] = 0
cases.append(f'case/{k} ' + ' '.join(f'{a}={b}' for a, b in kv.items()))
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
parser.add_argument('--java-only', action='store_true', help='run the oracle and stop')
args = parser.parse_args()
build = lab.LOCAL / 'rust-finalize-spawn-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'
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs']
tested = base.source_hashes([s for s in sources if s.exists()])
inputs = build / 'inputs.txt'
cases = corpus()
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):
path = build / (name + '.log')
with path.open('w', encoding='utf-8') as log:
try:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
log.flush()
raise SystemExit(f'{name} failed:\n' + path.read_text(errors='replace')[-4000:])
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', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaFinalizeSpawnOracle', inputs, build / 'server.txt'], 'server')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
if args.java_only:
print(f'{len(vanilla)} oracle lines')
return
halloween = vanilla[0].split()[1]
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_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/finalize_spawn_fixture'
run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12])
raise SystemExit(f'{len(bad)} of {len(vanilla)} lines differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged([s for s in sources if s.exists()], tested)
entities = sum(line.count(' | ') for line in vanilla) // 2
enchanted = sum(line.count('[minecraft:') for line in vanilla)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'entities': entities, 'enchanted_items': enchanted, 'sources_sha256': tested,
'scope': 'Mob.finalizeSpawn for every mob type and spawn reason: populateDefaultEquipmentSlots, '
'populateDefaultEquipmentEnchantments through the mob_spawn_equipment and pillager_spawn_crossbow '
'providers, drop chances, CanPickUpLoot, LeftHanded, the follow range spawn bonus, babies and '
'group data, jockeys (chicken, spider, strider, zombie horse, camel husk, zombie nautilus), '
'variants and sound variants, zombie attributes, spider effects, patrol leaders, villager types, '
'cube sizes, horse and llama attributes and the memories finalizeSpawn sets, with every draw of the '
'level random and of the entities\' own randoms.'})
print(f'{len(cases):,} finalizeSpawn cases match vanilla ({entities:,} entities, {enchanted:,} enchanted items)')
if __name__ == '__main__':
main()