Check spawn placements and spawn predicates exactly as SpawnPlacements does

mobs::spawn_rules ports SpawnPlacements over a SpawnLevel trait the game's
MobWorld implements: the placement types with per-type isValidSpawn
(leaves, ice, magma for fire-immune types) and isValidEmptySpawnBlock with
each type's dangerous and immune blocks, and every registered predicate in
vanilla's draw order: the dimension's monster light test and block light
limit, thunder, peaceful, spawn reasons, guardians' sky from below water,
drowned, bats, ghasts, ocelots, slimes (surface chance and slime chunks),
strays under powder snow, striders, turtles, polar bears, tropical fish,
nautiluses, silverfish and endermites near players, patrols and the
spawnable-on tags.

Divergences fixed on the way: nether monsters ignored light, hoglins and
piglins had extra checks, slimes spawned outside slime chunks, ocelots and
ghasts skipped their odds, bats ignored the surface and their draw order,
and several predicates read the wrong blocks.

tools/test_spawn_rules_parity.py: 18,669 cases over 87 entity types match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 22:16:57 +02:00
parent 723ec3bb8a
commit e6ef8c502b
7 changed files with 1227 additions and 154 deletions
@@ -0,0 +1,232 @@
//! Spawn placement and spawn predicate answers for differential tests against
//! vanilla (tools/test_spawn_rules_parity.py): reads the column-world cases of
//! `VanillaSpawnRulesOracle` and prints `mobs::spawn_rules`' answers.
//!
//! usage: spawn_rules_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
assets::Assets,
blocks::BlockFacts,
items::Items,
mobs::{
MobTypes,
data::MobData,
spawn_rules::{self, Dimension, Reason, SpawnLevel},
},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::{chunk::BlockState, registry::BlockStateId};
use std::{
collections::{BTreeMap, HashMap, HashSet},
fmt::Write as _,
fs,
path::Path,
};
struct Column<'a> {
facts: &'a BlockFacts,
data: &'a MobData,
block_tags: &'a HashMap<String, HashSet<String>>,
air: BlockStateId,
blocks: HashMap<i32, BlockStateId>,
x0: i32,
z0: i32,
sky: i32,
light: i32,
darken: i32,
thunder: bool,
sea: i32,
surface: i32,
seed: i64,
peaceful: bool,
dimension: Dimension,
biome: String,
slime: f32,
/// A player position and whether it is survival or adventure.
player: Option<([f64; 3], bool)>,
}
impl SpawnLevel for Column<'_> {
fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId {
if x != self.x0 || z != self.z0 {
return self.air;
}
self.blocks.get(&y).copied().unwrap_or(self.air)
}
fn facts(&self) -> &BlockFacts {
self.facts
}
fn mob_data(&self) -> &MobData {
self.data
}
fn block_tag(&self, tag: &str, block: &str) -> bool {
self.block_tags.get(tag).is_some_and(|s| s.contains(block))
}
fn biome_tag(&self, tag: &str, _: i32, _: i32, _: i32) -> bool {
self.data
.biome_tags
.get(tag)
.is_some_and(|s| s.contains(&self.biome))
}
fn sky_light(&self, _: i32, _: i32, _: i32) -> i32 {
self.sky
}
fn block_light(&self, _: i32, _: i32, _: i32) -> i32 {
self.light
}
fn sky_darken(&self) -> i32 {
self.darken
}
fn thundering(&self) -> bool {
self.thunder
}
fn sea_level(&self) -> i32 {
self.sea
}
fn world_surface(&self, _: i32, _: i32) -> i32 {
self.surface
}
fn peaceful(&self) -> bool {
self.peaceful
}
fn dimension(&self) -> Dimension {
self.dimension
}
fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 {
self.slime
}
fn world_seed(&self) -> i64 {
self.seed
}
fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool {
self.player.is_some_and(|(p, targetable)| {
let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2);
targetable && d < distance * distance
})
}
}
/// `name[key=value,...]`.
fn parse_state(spec: &str) -> BlockState {
let (name, props) = match spec.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (spec, ""),
};
let properties: BTreeMap<String, String> = props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect();
BlockState {
name: name.to_owned(),
properties,
}
}
fn reason(name: &str) -> Reason {
match name {
"chunk_generation" => Reason::ChunkGeneration,
"spawner" => Reason::Spawner,
"trial_spawner" => Reason::TrialSpawner,
"reinforcement" => Reason::Reinforcement,
"patrol" => Reason::Patrol,
"structure" => Reason::Structure,
"event" => Reason::Event,
"command" => Reason::Command,
_ => Reason::Natural,
}
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: spawn_rules_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let assets = Assets::load(root)?;
let registry = assets.registry;
let facts = BlockFacts::load(root, registry)?;
let data = MobData::load(root, &facts);
let items = Items::tags_only(root)?;
let types = MobTypes::load(root)?;
let mut out = String::new();
for raw in input.lines() {
if raw.trim().is_empty() {
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 Some(kind) = types.types.get(c["type"]) else {
let _ = writeln!(out, "{name} error unsupported {}", c["type"]);
continue;
};
let y: i32 = get("y", "64").parse()?;
let (x0, z0): (i32, i32) = (get("x", "8").parse()?, get("z", "8").parse()?);
let mut blocks = HashMap::new();
for (k, v) in &c {
if let Some(offset) = k.strip_prefix("at") {
let offset: i32 = offset.parse()?;
blocks.insert(y + offset, registry.resolve(&parse_state(v))?);
}
}
let player = c.get("player").map(|p| {
let f: Vec<&str> = p.split(',').collect();
let at = |i: usize, base: i32| f64::from(base) + f[i].parse::<f64>().unwrap_or(0.0);
let mode = f.get(3).copied().unwrap_or("survival");
(
[at(0, x0), at(1, y), at(2, z0)],
mode == "survival" || mode == "adventure",
)
});
let level = Column {
facts: &facts,
data: &data,
block_tags: &items.block_tags,
air: facts.air,
blocks,
x0,
z0,
sky: get("sky", "15").parse()?,
light: get("light", "0").parse()?,
darken: get("darken", "0").parse()?,
thunder: get("thunder", "0") == "1",
sea: get("sea", "63").parse()?,
surface: get("surface", "0").parse()?,
seed: get("wseed", "0").parse()?,
peaceful: get("difficulty", "normal") == "peaceful",
dimension: match get("dim", "minecraft:overworld").as_str() {
"minecraft:the_nether" => Dimension::Nether,
"minecraft:the_end" => Dimension::End,
_ => Dimension::Overworld,
},
biome: get("biome", "minecraft:plains"),
slime: get("slime", "0.0").parse()?,
player,
};
let mut random = LegacyRandom::new(get("seed", "0").parse()?);
let s = kind.species;
let ok = spawn_rules::is_spawn_position_ok(s, &level, x0, y, z0);
let rules = spawn_rules::check_spawn_rules(
s,
&level,
reason(&get("reason", "natural")),
&mut random,
x0,
y,
z0,
);
let next = random.next_int_bound(1000).unwrap_or(0);
let _ = writeln!(out, "{name} {ok} {rules} {next}");
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -467,6 +467,8 @@ impl Game<'_> {
block_tags: &self.res.items.block_tags,
biomes: &self.res.biomes,
mob_griefing: self.ui.rules.bool("mob_griefing"),
end: self.dim == Dim::End,
world_seed: self.level.seed,
difficulty: self.local_difficulty(
self.player
.as_ref()
+5
View File
@@ -47,6 +47,7 @@ pub mod riders;
pub mod shulker;
pub mod sniffer;
pub mod spawning;
pub mod spawn_rules;
pub mod species;
pub mod sulfur_cube;
pub mod tame;
@@ -903,6 +904,10 @@ pub struct MobWorld<'a> {
pub mob_griefing: bool,
/// `getCurrentDifficultyAt` near the player.
pub difficulty: spawning::LocalDifficulty,
/// The End (its dimension type's monster spawn light rules).
pub end: bool,
/// The world seed (slime chunks).
pub world_seed: i64,
}
impl Mob {
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
@@ -0,0 +1,589 @@
//! `SpawnPlacements`: each entity type's placement type
//! (`SpawnPlacementTypes.isSpawnPositionOk`) and spawn predicate
//! (`checkSpawnRules`), read through [`SpawnLevel`] so the game's world and a
//! differential test world answer the same questions. Random draws follow
//! vanilla's order.
use super::{Species, data};
use crate::blocks::{BlockFacts, Fluid};
use horizon_core::random::{RandomSource, slime_chunk_random};
use horizon_world::registry::BlockStateId;
/// `EntitySpawnReason`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
Natural,
ChunkGeneration,
Spawner,
TrialSpawner,
Reinforcement,
Patrol,
Structure,
Event,
Command,
SpawnItemUse,
MobSummoned,
Conversion,
Breeding,
Triggered,
Jockey,
Dispenser,
Bucket,
Load,
DimensionTravel,
}
impl Reason {
pub fn is_spawner(self) -> bool {
matches!(self, Self::Spawner | Self::TrialSpawner)
}
pub fn ignores_light(self) -> bool {
self == Self::TrialSpawner
}
}
/// The dimension type's monster spawn light rules.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dimension {
Overworld,
Nether,
End,
}
impl Dimension {
/// `monster_spawn_block_light_limit`.
fn block_light_limit(self) -> i32 {
match self {
Self::Nether => 15,
_ => 0,
}
}
/// `monster_spawn_light_level.sample`: uniform 0..=7 in the overworld.
fn light_test(self, random: &mut impl RandomSource) -> i32 {
match self {
Self::Overworld => random.next_int_bound(8).unwrap_or(0),
Self::Nether => 7,
Self::End => 15,
}
}
}
/// What spawn checks read from a level.
pub trait SpawnLevel {
fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId;
fn facts(&self) -> &BlockFacts;
fn mob_data(&self) -> &data::MobData;
fn block_tag(&self, tag: &str, block: &str) -> bool;
fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool;
/// `getBrightness(LightLayer.SKY / BLOCK)`.
fn sky_light(&self, x: i32, y: i32, z: i32) -> i32;
fn block_light(&self, x: i32, y: i32, z: i32) -> i32;
fn sky_darken(&self) -> i32;
fn thundering(&self) -> bool;
fn sea_level(&self) -> i32;
/// `getHeight(WORLD_SURFACE, x, z)`: above the highest non-air block.
fn world_surface(&self, x: i32, z: i32) -> i32;
fn peaceful(&self) -> bool;
fn dimension(&self) -> Dimension;
/// The `gameplay/surface_slime_spawn_chance` environment attribute.
fn surface_slime_chance(&self, x: i32, y: i32, z: i32) -> f32;
fn world_seed(&self) -> i64;
/// `getNearestPlayer(x, y, z, distance, true) != null`: a survival or
/// adventure player that close.
fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool;
}
fn name<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> &str {
&l.facts().get(l.state(x, y, z)).name
}
fn fluid<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> Fluid {
l.facts().get(l.state(x, y, z)).fluid
}
fn flags<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> u16 {
l.mob_data().state(l.state(x, y, z)).flags
}
fn tag<L: SpawnLevel>(l: &L, tag: &str, x: i32, y: i32, z: i32) -> bool {
l.block_tag(tag, name(l, x, y, z))
}
/// `getRawBrightness(pos, darkening)`.
fn raw_brightness<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32, darkening: i32) -> i32 {
l.block_light(x, y, z).max(l.sky_light(x, y, z) - darkening)
}
fn can_see_sky<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> bool {
l.sky_light(x, y, z) >= 15
}
/// `LevelReader.canSeeSkyFromBelowWater`.
fn can_see_sky_from_below_water<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> bool {
let sea = l.sea_level();
if y >= sea {
return can_see_sky(l, x, y, z);
}
if !can_see_sky(l, x, sea, z) {
return false;
}
((y + 1)..sea).all(|yy| {
let f = l.facts().get(l.state(x, yy, z));
f.dampening == 0 || f.fluid != Fluid::None
})
}
/// `EntityType.fireImmune`.
pub fn fire_immune(s: Species) -> bool {
use Species as S;
matches!(
s,
S::Blaze
| S::Ghast
| S::MagmaCube
| S::Shulker
| S::Strider
| S::Vex
| S::Warden
| S::Wither
| S::WitherSkeleton
| S::Zoglin
| S::ZombifiedPiglin
)
}
/// `EntityType.isAllowedInPeaceful`.
pub fn allowed_in_peaceful(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::Ghast
| S::Giant
| S::Guardian
| S::Hoglin
| S::Husk
| S::Illusioner
| S::MagmaCube
| S::Parched
| S::Phantom
| S::PiglinBrute
| S::Pillager
| S::Ravager
| S::Silverfish
| S::Skeleton
| S::Slime
| S::Spider
| S::Stray
| S::Vex
| S::Vindicator
| S::Warden
| S::Witch
| S::Wither
| S::WitherSkeleton
| S::Zoglin
| S::Zombie
| S::ZombieVillager
| S::ZombifiedPiglin
)
}
/// The block tag an entity type is `immuneTo`.
fn immune_tag(s: Species) -> Option<&'static str> {
use Species as S;
match s {
S::Fox => Some("minecraft:fox_immune_to"),
S::PolarBear => Some("minecraft:polar_bear_immune_to"),
S::SnowGolem => Some("minecraft:snow_golem_immune_to"),
S::Stray => Some("minecraft:stray_immune_to"),
S::Wither => Some("minecraft:wither_immune_to"),
S::WitherSkeleton => Some("minecraft:wither_skeleton_immune_to"),
_ => None,
}
}
/// `BlockState.isValidSpawn(level, pos, type)` for the block at a position.
pub fn is_valid_spawn<L: SpawnLevel>(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool {
if name(l, x, y, z) == "minecraft:magma_block" {
return fire_immune(s);
}
let bit = match s {
Species::Ocelot | Species::Parrot => data::VALID_SPAWN_LEAVES,
Species::PolarBear => data::VALID_SPAWN_ICE,
_ => data::VALID_SPAWN,
};
flags(l, x, y, z) & bit != 0
}
/// `NaturalSpawner.isValidEmptySpawnBlock` for an entity type.
pub fn is_valid_empty_spawn<L: SpawnLevel>(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool {
// The exported flag is the zombie's answer; only blocks a zombie finds
// dangerous can answer differently for another type.
if flags(l, x, y, z) & data::VALID_EMPTY_SPAWN != 0 {
return true;
}
let f = l.facts().get(l.state(x, y, z));
let block = &*f.name;
let burning = l.block_tag("minecraft:fire", block)
|| block == "minecraft:lava"
|| block == "minecraft:magma_block"
|| (block == "minecraft:campfire" || block == "minecraft:soul_campfire") && f.emission > 0
|| block == "minecraft:lava_cauldron";
let other = matches!(
block,
"minecraft:wither_rose"
| "minecraft:sweet_berry_bush"
| "minecraft:cactus"
| "minecraft:powder_snow"
);
if !burning && !other {
return false;
}
let immune = immune_tag(s).is_some_and(|t| l.block_tag(t, block));
let dangerous = !immune && (burning && !fire_immune(s) || other);
!dangerous
&& !f.full_collision
&& f.fluid == Fluid::None
&& !l.block_tag("minecraft:prevent_mob_spawning_inside", block)
}
/// `SpawnPlacements.isSpawnPositionOk`.
pub fn is_spawn_position_ok<L: SpawnLevel>(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool {
let id = format!("minecraft:{}", super::species::def(s).name);
match l.mob_data().placement(&id) {
data::Placement::OnGround => {
is_valid_spawn(s, l, x, y - 1, z)
&& is_valid_empty_spawn(s, l, x, y, z)
&& is_valid_empty_spawn(s, l, x, y + 1, z)
}
data::Placement::InWater => {
fluid(l, x, y, z) == Fluid::Water && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0
}
data::Placement::InLava => fluid(l, x, y, z) == Fluid::Lava,
data::Placement::NoRestrictions => true,
}
}
/// `Monster.isDarkEnoughToSpawn`.
pub fn is_dark_enough<L: SpawnLevel>(l: &L, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool {
if l.sky_light(x, y, z) > random.next_int_bound(32).unwrap_or(0) {
return false;
}
let dim = l.dimension();
let limit = dim.block_light_limit();
if limit < 15 && l.block_light(x, y, z) > limit {
return false;
}
let darken = if l.thundering() { 10 } else { l.sky_darken() };
let brightness = raw_brightness(l, x, y, z, darken);
brightness <= dim.light_test(random)
}
/// `Animal.isBrightEnoughToSpawn`.
fn bright<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> bool {
raw_brightness(l, x, y, z, 0) > 8
}
/// `Mob.checkMobSpawnRules`.
fn mob_rules<L: SpawnLevel>(s: Species, l: &L, reason: Reason, x: i32, y: i32, z: i32) -> bool {
reason.is_spawner() || is_valid_spawn(s, l, x, y - 1, z)
}
/// `Monster.checkMonsterSpawnRules`.
fn monster_rules<L: SpawnLevel>(
s: Species,
l: &L,
reason: Reason,
random: &mut impl RandomSource,
x: i32,
y: i32,
z: i32,
) -> bool {
(reason.ignores_light() || is_dark_enough(l, random, x, y, z)) && mob_rules(s, l, reason, x, y, z)
}
/// `Animal.checkAnimalSpawnRules` with the given spawnable-on tag.
fn animal_rules<L: SpawnLevel>(l: &L, reason: Reason, on: &str, x: i32, y: i32, z: i32) -> bool {
let bright = reason.ignores_light() || bright(l, x, y, z);
tag(l, on, x, y - 1, z) && bright
}
/// `WaterAnimal.checkSurfaceWaterAnimalSpawnRules`.
fn surface_water<L: SpawnLevel>(l: &L, x: i32, y: i32, z: i32) -> bool {
let sea = l.sea_level();
y >= sea - 13
&& y <= sea
&& fluid(l, x, y - 1, z) == Fluid::Water
&& name(l, x, y + 1, z) == "minecraft:water"
}
/// `SpawnPlacements.checkSpawnRules`.
pub fn check_spawn_rules<L: SpawnLevel>(
s: Species,
l: &L,
reason: Reason,
random: &mut impl RandomSource,
x: i32,
y: i32,
z: i32,
) -> bool {
use Species as S;
if !allowed_in_peaceful(s) && l.peaceful() {
return false;
}
let below = |l: &L| name(l, x, y - 1, z).to_owned();
match s {
S::Axolotl => tag(l, "minecraft:axolotls_spawnable_on", x, y - 1, z),
S::Cod | S::Pufferfish | S::Salmon | S::Dolphin | S::Squid => surface_water(l, x, y, z),
S::Drowned => {
if fluid(l, x, y - 1, z) != Fluid::Water && !reason.is_spawner() {
return false;
}
let frequent = l.biome_tag("minecraft:more_frequent_drowned_spawns", x, y, z);
let can_spawn = !l.peaceful()
&& (reason.ignores_light() || is_dark_enough(l, random, x, y, z))
&& (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water);
if !can_spawn || !reason.is_spawner() && reason != Reason::Reinforcement {
if frequent {
random.next_int_bound(15).unwrap_or(1) == 0 && can_spawn
} else {
random.next_int_bound(40).unwrap_or(1) == 0 && y < l.sea_level() - 5 && can_spawn
}
} else {
true
}
}
S::Guardian | S::ElderGuardian => {
(random.next_int_bound(20).unwrap_or(1) == 0 || !can_see_sky_from_below_water(l, x, y, z))
&& !l.peaceful()
&& (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water)
&& fluid(l, x, y - 1, z) == Fluid::Water
}
S::TropicalFish => {
fluid(l, x, y - 1, z) == Fluid::Water
&& name(l, x, y + 1, z) == "minecraft:water"
&& (l.biome_tag("minecraft:allows_tropical_fish_spawns_at_any_height", x, y, z)
|| surface_water(l, x, y, z))
}
S::Armadillo => tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::Bat => {
if y >= l.world_surface(x, z) || random.next_boolean() {
return false;
}
if raw_brightness(l, x, y, z, l.sky_darken()) > random.next_int_bound(4).unwrap_or(0) {
return false;
}
tag(l, "minecraft:bats_spawnable_on", x, y - 1, z) && mob_rules(s, l, reason, x, y, z)
}
S::Blaze | S::Breeze | S::Zoglin => mob_rules(s, l, reason, x, y, z),
S::Camel => tag(l, "minecraft:camels_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::CamelHusk | S::Husk | S::Parched => {
monster_rules(s, l, reason, random, x, y, z)
&& (reason.is_spawner() || can_see_sky(l, x, y, z))
}
S::Chicken
| S::Cow
| S::Donkey
| S::HappyGhast
| S::Horse
| S::Llama
| S::Mule
| S::Pig
| S::Sheep
| S::Cat
| S::Panda
| S::TraderLlama => animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z),
S::Endermite | S::Silverfish => {
if !mob_rules(s, l, reason, x, y, z) {
return false;
}
reason.is_spawner()
|| !l.player_near(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5, 5.0)
}
S::IronGolem | S::SnowGolem | S::Villager | S::Phantom | S::Shulker
| S::WanderingTrader => mob_rules(s, l, reason, x, y, z),
S::Frog => tag(l, "minecraft:frogs_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::Ghast => {
!l.peaceful()
&& random.next_int_bound(20).unwrap_or(1) == 0
&& mob_rules(s, l, reason, x, y, z)
}
S::GlowSquid => {
y <= l.sea_level() - 33
&& raw_brightness(l, x, y, z, 0) == 0
&& name(l, x, y, z) == "minecraft:water"
}
S::Goat => tag(l, "minecraft:goats_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::MagmaCube => !l.peaceful(),
S::SulfurCube => true,
S::Mooshroom => tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::Nautilus => {
let sea = l.sea_level();
y >= sea - 25
&& y <= sea - 5
&& fluid(l, x, y - 1, z) == Fluid::Water
&& name(l, x, y + 1, z) == "minecraft:water"
}
S::Ocelot => random.next_int_bound(3).unwrap_or(0) != 0,
S::Parrot => tag(l, "minecraft:parrots_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::Hoglin | S::Piglin => below(l) != "minecraft:nether_wart_block",
S::Pillager => l.block_light(x, y, z) <= 8 && mob_rules(s, l, reason, x, y, z),
S::PolarBear => {
if l.biome_tag("minecraft:polar_bears_spawn_on_alternate_blocks", x, y, z) {
bright(l, x, y, z)
&& tag(l, "minecraft:polar_bears_spawnable_on_alternate", x, y - 1, z)
} else {
animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z)
}
}
S::Rabbit => tag(l, "minecraft:rabbits_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::SkeletonHorse => {
if reason.is_spawner() {
reason.ignores_light() || bright(l, x, y, z)
} else {
animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z)
}
}
S::Slime => slime_rules(s, l, reason, random, x, y, z),
S::Stray => {
let mut sky = y + 1;
while name(l, x, sky, z) == "minecraft:powder_snow" {
sky += 1;
}
monster_rules(s, l, reason, random, x, y, z)
&& (reason.is_spawner() || can_see_sky(l, x, sky - 1, z))
}
S::Strider => {
let mut up = y + 1;
while fluid(l, x, up, z) == Fluid::Lava {
up += 1;
}
l.facts().is_air(l.state(x, up, z))
}
S::Turtle => {
y < l.sea_level() + 4 && tag(l, "minecraft:sand", x, y - 1, z) && bright(l, x, y, z)
}
S::Wolf => tag(l, "minecraft:wolves_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::ZombifiedPiglin => !l.peaceful() && below(l) != "minecraft:nether_wart_block",
S::Fox => tag(l, "minecraft:foxes_spawnable_on", x, y - 1, z) && bright(l, x, y, z),
S::Bogged
| S::CaveSpider
| S::Creeper
| S::Enderman
| S::Giant
| S::Skeleton
| S::Spider
| S::Witch
| S::Wither
| S::WitherSkeleton
| S::Creaking
| S::Zombie
| S::ZombieHorse
| S::ZombieVillager
| S::Evoker
| S::Illusioner
| S::Ravager
| S::Vex
| S::Vindicator
| S::Warden => monster_rules(s, l, reason, random, x, y, z),
// Types without a SpawnPlacements registration.
_ => true,
}
}
/// `Slime.checkSlimeSpawnRules`.
fn slime_rules<L: SpawnLevel>(
s: Species,
l: &L,
reason: Reason,
random: &mut impl RandomSource,
x: i32,
y: i32,
z: i32,
) -> bool {
if l.peaceful() {
return false;
}
if reason.is_spawner() {
return mob_rules(s, l, reason, x, y, z);
}
if l.biome_tag("minecraft:allows_surface_slime_spawns", x, y, z) && y > 50 && y < 70 {
let chance = l.surface_slime_chance(x, y, z);
if random.next_float() < chance
&& raw_brightness(l, x, y, z, l.sky_darken()) <= random.next_int_bound(8).unwrap_or(0)
{
return mob_rules(s, l, reason, x, y, z);
}
}
let slime_chunk = slime_chunk_random(x >> 4, z >> 4, l.world_seed(), 987_234_911)
.next_int_bound(10)
.unwrap_or(1)
== 0;
if random.next_int_bound(10).unwrap_or(1) == 0 && slime_chunk && y < 40 {
return mob_rules(s, l, reason, x, y, z);
}
false
}
impl SpawnLevel for super::MobWorld<'_> {
fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId {
self.world.block(x, y, z)
}
fn facts(&self) -> &BlockFacts {
self.facts
}
fn mob_data(&self) -> &data::MobData {
self.data
}
fn block_tag(&self, tag: &str, block: &str) -> bool {
self.has_tag(tag, block)
}
fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool {
let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else {
return false;
};
let biome = &self.biomes.get(chunk.biome(x, y, z)).name;
self.data
.biome_tags
.get(tag.trim_start_matches('#'))
.is_some_and(|members| members.contains(biome))
}
fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 {
if self.nether || self.end {
return 0;
}
i32::from(self.world.light(x, y, z) >> 4)
}
fn block_light(&self, x: i32, y: i32, z: i32) -> i32 {
i32::from(self.world.light(x, y, z) & 15)
}
fn sky_darken(&self) -> i32 {
super::MobWorld::sky_darken(self)
}
fn thundering(&self) -> bool {
self.thundering
}
fn sea_level(&self) -> i32 {
if self.nether { 32 } else { 63 }
}
fn world_surface(&self, x: i32, z: i32) -> i32 {
let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT;
(crate::chunk::MIN_Y..top)
.rev()
.find(|&y| !self.facts.is_air(self.world.block(x, y, z)))
.map_or(crate::chunk::MIN_Y, |y| y + 1)
}
fn peaceful(&self) -> bool {
self.difficulty.effective == 0.0
}
fn dimension(&self) -> Dimension {
if self.nether {
Dimension::Nether
} else if self.end {
Dimension::End
} else {
Dimension::Overworld
}
}
fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 {
let phase = self.day_time.div_euclid(24000).rem_euclid(8) as usize;
0.5 * super::spawning::MOON_BRIGHTNESS[phase]
}
fn world_seed(&self) -> i64 {
self.world_seed
}
fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool {
self.player.as_ref().is_some_and(|p| {
let d = (p.position.x - x).powi(2) + (p.position.y - y).powi(2) + (p.position.z - z).powi(2);
p.alive && !p.creative && !p.spectator && d < distance * distance
})
}
}
+13 -154
View File
@@ -2,8 +2,7 @@
//! species' spawn predicate (`checkAnimalSpawnRules`, `checkMonsterSpawnRules`,
//! water animals, bats...), and `finalizeSpawn` (variants, colours, babies,
//! equipment).
use super::{Mob, MobWorld, Species, data, farm::Climate};
use crate::blocks::Fluid;
use super::{Mob, MobWorld, Species, farm::Climate};
use horizon_core::random::RandomSource;
/// Biome facts finalizeSpawn and the spawn rules read.
@@ -27,44 +26,11 @@ pub struct BiomeFacts {
/// `spawns_coral_variant_zombie_nautilus` (the warm ocean).
pub coral_nautilus: bool,
}
/// SpawnPlacementTypes for the species.
/// `SpawnPlacements.isSpawnPositionOk` for the species.
pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
let id = format!("minecraft:{}", super::species::def(species).name);
match w.data.placement(&id) {
data::Placement::OnGround => {
let below = w.data.state(w.world.block(x, y - 1, z));
let valid = match species {
Species::Ocelot | Species::Parrot => below.flags & data::VALID_SPAWN_LEAVES != 0,
Species::PolarBear => below.flags & data::VALID_SPAWN_ICE != 0,
_ => below.flags & data::VALID_SPAWN != 0,
};
valid && empty(w, x, y, z) && empty(w, x, y + 1, z)
}
data::Placement::InWater => {
w.fluid(x, y, z) == Fluid::Water
&& w.data.state(w.world.block(x, y + 1, z)).flags & data::REDSTONE_CONDUCTOR == 0
}
data::Placement::InLava => w.fluid(x, y, z) == Fluid::Lava,
data::Placement::NoRestrictions => true,
}
super::spawn_rules::is_spawn_position_ok(species, w, x, y, z)
}
fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
w.data.state(w.world.block(x, y, z)).flags & data::VALID_EMPTY_SPAWN != 0
}
/// Monster.isDarkEnoughToSpawn (overworld: sky light vs random(32), block light 0).
pub fn dark_enough(w: &MobWorld, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool {
let light = w.world.light(x, y, z);
let (sky, block) = (i32::from(light >> 4), i32::from(light & 15));
if sky > random.next_int_bound(32).unwrap_or(0) {
return false;
}
if block > 0 {
return false;
}
let darken = if w.thundering { 10 } else { w.sky_darken() };
(sky - darken).max(0) <= random.next_int_bound(8).unwrap_or(0)
}
/// The species' checkSpawnRules for natural spawns.
/// `SpawnPlacements.checkSpawnRules` for a natural spawn.
pub fn spawn_rules_ok(
species: Species,
w: &MobWorld,
@@ -73,122 +39,15 @@ pub fn spawn_rules_ok(
y: i32,
z: i32,
) -> bool {
use Species as S;
let below = w.block_name(x, y - 1, z).to_owned();
let light = w.world.light(x, y, z);
let raw = i32::from(light >> 4).max(i32::from(light & 15));
match species {
// Guardian.checkGuardianSpawnRules.
S::Guardian | S::ElderGuardian => {
let sky_from_below = || {
let sea = 63;
if y >= sea {
return w.can_see_sky(x, y, z);
}
if !w.can_see_sky(x, sea, z) {
return false;
}
((y + 1)..sea).all(|yy| {
let f = w.facts.get(w.world.block(x, yy, z));
!f.full_collision || f.fluid != Fluid::None
})
};
(random.next_int_bound(20).unwrap_or(1) == 0 || !sky_from_below())
&& w.fluid(x, y, z) == Fluid::Water
&& w.fluid(x, y - 1, z) == Fluid::Water
}
// Animal.checkAnimalSpawnRules: animals_spawnable_on below and bright.
S::Pig
| S::Cow
| S::Sheep
| S::Chicken
| S::Horse
| S::Donkey
| S::Llama
| S::Camel
| S::Wolf
| S::Cat
| S::Fox
| S::Rabbit
| S::Goat
| S::Panda
| S::Armadillo
| S::Mooshroom
| S::Turtle
| S::Frog
| S::Bee => {
let tag = match species {
S::Mooshroom => "minecraft:mooshrooms_spawnable_on",
S::Camel => "minecraft:camels_spawnable_on",
S::Wolf => "minecraft:wolves_spawnable_on",
S::Fox => "minecraft:foxes_spawnable_on",
S::Rabbit => "minecraft:rabbits_spawnable_on",
S::Goat => "minecraft:goats_spawnable_on",
S::Armadillo => "minecraft:armadillo_spawnable_on",
S::Turtle => "minecraft:turtles_spawnable_on",
S::Frog => "minecraft:frogs_spawnable_on",
_ => "minecraft:animals_spawnable_on",
};
w.has_tag(tag, &below) && raw > 8
}
S::PolarBear => {
w.has_tag("minecraft:polar_bears_spawnable_on_alternate", &below)
|| w.has_tag("minecraft:animals_spawnable_on", &below) && raw > 8
}
S::Ocelot | S::Parrot => {
(w.has_tag("minecraft:parrots_spawnable_on", &below)
|| below.contains("leaves")
|| below == "minecraft:grass_block")
&& raw > 8
}
S::Bat => {
// Bat.checkBatSpawnRules: below sea level, dark.
if y >= 63 {
return false;
}
let block = i32::from(light & 15).max(i32::from(light >> 4));
block <= random.next_int_bound(4).unwrap_or(0)
}
S::Slime => {
// Swamp at night by moon brightness, or slime chunks below y 40.
y < 40 && random.next_int_bound(10).unwrap_or(1) == 0
}
// GlowSquid.checkGlowSquidSpawnRules: deep, pitch dark water.
S::GlowSquid => y <= 63 - 33 && light == 0 && w.block_name(x, y, z) == "minecraft:water",
S::Squid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => {
// WaterAnimal.checkSurfaceWaterAnimalSpawnRules: sea level - 13 ..= sea level.
(50..=63).contains(&y)
&& w.fluid(x, y - 1, z) == Fluid::Water
&& w.block_name(x, y + 1, z) == "minecraft:water"
}
S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay",
S::Strider => w.fluid(x, y, z) == Fluid::Lava,
S::Ghast
| S::MagmaCube
| S::ZombifiedPiglin
| S::Piglin
| S::Hoglin
| S::Blaze
| S::WitherSkeleton
| S::Enderman
if w.nether =>
{
!w.block_name(x, y - 1, z).contains("nether_wart_block") || species == S::Ghast
}
// Monster.checkSurfaceMonstersSpawnRules.
S::Husk | S::Stray | S::CamelHusk => {
dark_enough(w, random, x, y, z) && w.can_see_sky(x, y, z)
}
// AbstractNautilus.checkNautilusSpawnRules.
S::Nautilus => super::nautilus::spawn_rules_ok(w, x, y, z),
// SulfurCube.checkSulfurCubeSpawnRules: anywhere it fits.
S::SulfurCube => true,
S::Drowned => w.fluid(x, y, z) == Fluid::Water && dark_enough(w, random, x, y, z),
_ => {
// Monster.checkMonsterSpawnRules
!w.nether && dark_enough(w, random, x, y, z) || w.nether
}
}
super::spawn_rules::check_spawn_rules(
species,
w,
super::spawn_rules::Reason::Natural,
random,
x,
y,
z,
)
}
/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs.
/// `DifficultyInstance`: the local difficulty at a position.
@@ -0,0 +1,204 @@
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 net.minecraft.SharedConstants;
import net.minecraft.core.*;
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.tags.TagLoader;
import net.minecraft.util.RandomSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.biome.Biome;
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.levelgen.Heightmap;
import net.minecraft.world.level.material.FluidState;
/**
* Original oracle: SpawnPlacements.isSpawnPositionOk and checkSpawnRules for an
* entity type at a position of a controlled column world. The stand-in
* ServerLevel answers block states from the case (air elsewhere), uniform sky
* and block light, the sky darkening, thunder, difficulty, dimension type,
* biome, sea level, WORLD_SURFACE height, world seed, the surface slime spawn
* chance and an optional nearby player. Each case prints the two answers and
* the next nextInt(1000) of its random, which pins the number of draws.
*/
public final class VanillaSpawnRulesOracle {
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 final class Lvl extends ServerLevel {
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
RegistryAccess registries;
Map<Integer, BlockState> column = new HashMap<>();
int x0, z0, sky, block, darken, sea, surface;
boolean thunder;
long seed;
Difficulty difficulty;
DimensionType dimension;
Holder<Biome> biome;
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
List<Player> playerList = new ArrayList<>();
WorldBorder border = new WorldBorder();
int next = 1;
@Override public RegistryAccess registryAccess() { return registries; }
@Override public Difficulty getDifficulty() { return difficulty; }
@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 BlockState getBlockState(BlockPos pos) {
if (pos.getX() != x0 || pos.getZ() != z0) return Blocks.AIR.defaultBlockState();
return column.getOrDefault(pos.getY(), Blocks.AIR.defaultBlockState());
}
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
@Override public int getBrightness(LightLayer layer, BlockPos pos) { return layer == LightLayer.SKY ? sky : block; }
@Override public int getRawBrightness(BlockPos pos, int darkening) { return Math.max(block, sky - darkening); }
@Override public int getSkyDarken() { return darken; }
@Override public boolean isThundering() { return thunder; }
@Override public int getSeaLevel() { return sea; }
@Override public int getHeight(Heightmap.Types type, int x, int z) { return surface; }
@Override public long getSeed() { return seed; }
@Override public DimensionType dimensionType() { return dimension; }
@Override public Holder<Biome> getBiome(BlockPos pos) { return biome; }
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
@Override public WorldBorder getWorldBorder() { return border; }
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public List players() { return playerList; }
}
static final class OraclePlayer extends Player {
final GameType mode;
OraclePlayer(Level level, GameType mode) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); this.mode = mode; }
@Override public GameType gameMode() { return mode; }
@Override public boolean isCreative() { return mode == GameType.CREATIVE; }
@Override public boolean isSpectator() { return mode == GameType.SPECTATOR; }
@Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); }
}
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();
staticTags.forEach(Registry.PendingTags::apply);
var access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess();
Lvl level = (Lvl) alloc(Lvl.class);
level.registries = access;
level.column = new HashMap<>();
level.playerList = new ArrayList<>();
level.border = new WorldBorder();
put(level, Level.class, "random", RandomSource.create(0L));
var biomes = access.lookupOrThrow(Registries.BIOME);
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
var blocks = access.lookupOrThrow(Registries.BLOCK);
if (args.length > 2 && args[2].equals("facts")) {
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
for (var type : BuiltInRegistries.ENTITY_TYPE)
w.println(BuiltInRegistries.ENTITY_TYPE.getKey(type) + " peaceful=" + type.isAllowedInPeaceful() + " fire_immune=" + type.fireImmune()
+ " placement=" + SpawnPlacements.getPlacementType(type) + " heightmap=" + SpawnPlacements.getHeightmapType(type));
}
System.exit(0);
}
List<String> 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()) 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 {
int y = Integer.parseInt(c.getOrDefault("y", "64"));
level.x0 = Integer.parseInt(c.getOrDefault("x", "8"));
level.z0 = Integer.parseInt(c.getOrDefault("z", "8"));
level.column.clear();
for (var e : c.entrySet()) {
if (e.getKey().startsWith("at")) {
int offset = Integer.parseInt(e.getKey().substring(2));
level.column.put(y + offset, net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blocks, e.getValue(), false).blockState());
}
}
level.sky = Integer.parseInt(c.getOrDefault("sky", "15"));
level.block = Integer.parseInt(c.getOrDefault("light", "0"));
level.darken = Integer.parseInt(c.getOrDefault("darken", "0"));
level.thunder = c.getOrDefault("thunder", "0").equals("1");
level.sea = Integer.parseInt(c.getOrDefault("sea", "63"));
level.surface = Integer.parseInt(c.getOrDefault("surface", "0"));
level.seed = Long.parseLong(c.getOrDefault("wseed", "0"));
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
level.dimension = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")))).value();
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder()
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
.set(net.minecraft.world.attribute.EnvironmentAttributes.SURFACE_SLIME_SPAWN_CHANCE, Float.parseFloat(c.getOrDefault("slime", "0.0")))
.build())
.build();
level.playerList.clear();
if (c.containsKey("player")) {
String[] p = c.get("player").split(",");
Player player = new OraclePlayer(level, GameType.byName(p.length > 3 ? p[3] : "survival"));
player.setPos(level.x0 + Double.parseDouble(p[0]), y + Double.parseDouble(p[1]), level.z0 + Double.parseDouble(p[2]));
level.playerList.add(player);
}
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type")));
EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "natural").toUpperCase(Locale.ROOT));
BlockPos pos = new BlockPos(level.x0, y, level.z0);
RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
boolean ok = SpawnPlacements.isSpawnPositionOk(type, level, pos);
boolean rules = SpawnPlacements.checkSpawnRules(type, level, reason, pos, random);
w.println(c.get("name") + " " + ok + " " + rules + " " + random.nextInt(1000));
} catch (Throwable t) {
Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t;
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);
}
}
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Compare spawn placement checks and spawn predicates with vanilla.
Java (VanillaSpawnRulesOracle) runs SpawnPlacements.isSpawnPositionOk and
checkSpawnRules on a stand-in ServerLevel holding one column of blocks with
uniform light; Rust (spawn_rules_fixture) runs horizon_client::mobs::spawn_rules
on the same column. Every mob type is tried on surfaces, caves, water, lava,
the nether and the end, dangerous blocks, light levels, thunder, difficulty,
biomes, slime chunks, nearby players and several spawn reasons; each case
also prints the next draw of its random, pinning the number of draws.
"""
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 types that are not Horizon mob types or not mobs at all.
SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'}
SCENARIOS = {
'grass-day': dict(b=dict(m1='minecraft:grass_block'), sky=15, surface=64),
'grass-night': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, surface=64),
'grass-dusk': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=7, surface=64),
'grass-thunder': dict(b=dict(m1='minecraft:grass_block'), sky=15, thunder=1, surface=64),
'grass-peaceful': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, difficulty='peaceful', surface=64),
'grass-torch': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, light=9, surface=64),
'cave-dark': dict(b=dict(m1='minecraft:stone'), sky=0, y=20, surface=80),
'cave-lit1': dict(b=dict(m1='minecraft:stone'), sky=0, light=1, y=20, surface=80),
'cave-lit8': dict(b=dict(m1='minecraft:deepslate'), sky=0, light=8, y=-20, surface=80),
'cave-lit12': dict(b=dict(m1='minecraft:stone'), sky=0, light=12, y=20, surface=80),
'cave-dim': dict(b=dict(m1='minecraft:stone'), sky=3, y=40, surface=80),
'water-surface': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=60, surface=64, biome='minecraft:ocean'),
'water-warm': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=58, surface=64, biome='minecraft:warm_ocean'),
'water-deep': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=25, surface=64, biome='minecraft:deep_ocean'),
'water-deep-lit': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, light=3, y=25, surface=64, biome='minecraft:lukewarm_ocean'),
'water-mid': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=45, surface=64, biome='minecraft:cold_ocean'),
'water-roofed': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water', p3='minecraft:stone'), sky=0, y=50, surface=64, biome='minecraft:ocean'),
'water-river': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=50, surface=64, biome='minecraft:river', darken=11),
'water-conductor': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:stone'), sky=15, y=60, surface=64),
'water-seagrass': dict(b=dict(m1='minecraft:sand', p0='minecraft:water', p1='minecraft:water'), sky=15, y=55, surface=64, biome='minecraft:ocean'),
'water-clay': dict(b=dict(m1='minecraft:clay', p0='minecraft:water', p1='minecraft:water'), sky=0, y=10, surface=64, biome='minecraft:lush_caves'),
'lava-nether': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava', p1='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'),
'lava-open': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'),
'nether-dark': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'),
'nether-lit7': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=7, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-lit8': dict(b=dict(m1='minecraft:crimson_nylium'), sky=0, light=8, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-wart': dict(b=dict(m1='minecraft:nether_wart_block'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-soul': dict(b=dict(m1='minecraft:soul_sand'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'),
'nether-magma': dict(b=dict(m1='minecraft:magma_block'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'),
'end': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=0, y=60, dim='minecraft:the_end', biome='minecraft:the_end'),
'end-lit': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=14, y=60, dim='minecraft:the_end', biome='minecraft:end_highlands'),
'ice-frozen': dict(b=dict(m1='minecraft:ice'), sky=15, y=63, surface=64, biome='minecraft:frozen_ocean'),
'ice-plains': dict(b=dict(m1='minecraft:packed_ice'), sky=15, y=64, surface=64, biome='minecraft:snowy_plains'),
'snow-block': dict(b=dict(m1='minecraft:snow_block'), sky=15, darken=11, y=70, surface=70, biome='minecraft:snowy_plains'),
'snow-layer': dict(b=dict(m1='minecraft:grass_block[snowy=true]', p0='minecraft:snow'), sky=15, y=70, surface=71, biome='minecraft:snowy_taiga'),
'powder-snow-stray': dict(b=dict(m1='minecraft:snow_block', p1='minecraft:powder_snow', p2='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=93, biome='minecraft:frozen_peaks'),
'sand-beach': dict(b=dict(m1='minecraft:sand'), sky=15, y=63, surface=64, biome='minecraft:beach'),
'sand-desert': dict(b=dict(m1='minecraft:sand'), sky=15, darken=11, y=70, surface=70, biome='minecraft:desert'),
'red-sand': dict(b=dict(m1='minecraft:red_sand'), sky=15, y=80, surface=80, biome='minecraft:badlands'),
'leaves-jungle': dict(b=dict(m1='minecraft:jungle_leaves'), sky=15, y=90, surface=90, biome='minecraft:jungle'),
'grass-jungle': dict(b=dict(m1='minecraft:grass_block'), sky=15, y=70, surface=70, biome='minecraft:jungle'),
'mycelium': dict(b=dict(m1='minecraft:mycelium'), sky=15, y=70, surface=70, biome='minecraft:mushroom_fields'),
'podzol': dict(b=dict(m1='minecraft:podzol'), sky=15, y=70, surface=70, biome='minecraft:old_growth_pine_taiga'),
'mud-swamp': dict(b=dict(m1='minecraft:mud'), sky=15, y=62, surface=62, biome='minecraft:mangrove_swamp'),
'stone-peaks': dict(b=dict(m1='minecraft:stone'), sky=15, y=160, surface=160, biome='minecraft:jagged_peaks'),
'coarse-savanna': dict(b=dict(m1='minecraft:coarse_dirt'), sky=15, y=70, surface=70, biome='minecraft:savanna'),
'slab-bottom': dict(b=dict(m1='minecraft:oak_slab[type=bottom]'), sky=0, y=40, surface=80),
'slab-top': dict(b=dict(m1='minecraft:oak_slab[type=top]'), sky=0, y=40, surface=80),
'glass': dict(b=dict(m1='minecraft:glass'), sky=0, y=40, surface=80),
'glowstone': dict(b=dict(m1='minecraft:glowstone'), sky=0, light=15, y=40, surface=80),
'fire': dict(b=dict(m1='minecraft:netherrack', p0='minecraft:fire'), sky=0, light=15, y=40, surface=80),
'soul-fire': dict(b=dict(m1='minecraft:soul_soil', p0='minecraft:soul_fire'), sky=0, light=10, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'),
'wither-rose': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:wither_rose'), sky=0, y=40, surface=80),
'berry-bush': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:sweet_berry_bush'), sky=15, y=70, surface=70, biome='minecraft:taiga'),
'cactus': dict(b=dict(m1='minecraft:sand', p0='minecraft:cactus'), sky=0, y=70, surface=72, biome='minecraft:desert'),
'powder-snow-feet': dict(b=dict(m1='minecraft:snow_block', p0='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=91, biome='minecraft:snowy_slopes'),
'campfire': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=true]'), sky=0, light=15, y=40, surface=80),
'campfire-out': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=false]'), sky=0, y=40, surface=80),
'rail': dict(b=dict(m1='minecraft:stone', p0='minecraft:rail'), sky=0, y=40, surface=80),
'redstone-torch': dict(b=dict(m1='minecraft:stone', p0='minecraft:redstone_torch'), sky=0, light=7, y=40, surface=80),
'tall-grass': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:short_grass', p1='minecraft:air'), sky=15, darken=11, y=70, surface=70),
'low-ceiling': dict(b=dict(m1='minecraft:stone', p1='minecraft:stone'), sky=0, y=40, surface=80),
'swamp-surface': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=62, surface=63, biome='minecraft:swamp', slime=0.5),
'swamp-full-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=4, y=64, surface=65, biome='minecraft:swamp', slime=0.5),
'swamp-new-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=63, surface=64, biome='minecraft:swamp', slime=0.0),
'bat-cave': dict(b=dict(m1='minecraft:stone'), sky=0, y=10, surface=80),
'bat-surface': dict(b=dict(m1='minecraft:stone'), sky=0, y=79, surface=79),
}
REASONS = ['natural', 'natural', 'natural', 'chunk_generation', 'spawner', 'trial_spawner', 'reinforcement', 'patrol']
def corpus(types):
rng = random.Random(0x5350574E)
cases = []
for t in types:
n = t.split(':')[1]
for name, s in SCENARIOS.items():
for k in range(3):
kv = {k2: v for k2, v in s.items() if k2 != 'b'}
kv.setdefault('y', 64)
for key, block in s['b'].items():
kv['at' + ('-' if key[0] == 'm' else '') + key[1:]] = block
kv['reason'] = REASONS[k] if k == 0 else rng.choice(REASONS)
kv['seed'] = rng.randrange(-2**47, 2**47)
cases.append(f'{n}/{name}/{k} type={t} ' + ' '.join(f'{a}={b}' for a, b in kv.items()))
# Slime chunks: deep caves at many chunk positions and world seeds.
if n in ('slime', 'zombie'):
for k in range(600 if n == 'slime' else 60):
cases.append(f'{n}/slime-chunk/{k} type={t} at-1=minecraft:stone sky=0 y={rng.randrange(-60, 45)} '
f'x={rng.randrange(-4000, 4000)} z={rng.randrange(-4000, 4000)} wseed={rng.randrange(-2**63, 2**63)} '
f'seed={rng.randrange(-2**47, 2**47)} reason=natural surface=80')
# Nearby players (silverfish and endermite refuse to spawn next to a targetable one).
for k, player in enumerate(['1,0,1,survival', '1,0,1,creative', '4,0,4,survival', '3,1,3,adventure', '0,4.4,0,survival',
'2,2,2,spectator']):
cases.append(f'{n}/player/{k} type={t} at-1=minecraft:stone sky=0 y=20 surface=80 player={player} '
f'seed={rng.randrange(-2**47, 2**47)} reason={rng.choice(REASONS)}')
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-spawn-rules-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'
entity_types = json.loads((resources / 'entity-types.json').read_text())
types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.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.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_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/spawn_rules_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
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]}')
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}\n rust {b}' for a, b in bad[:40])
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
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), 'scenarios': sorted(SCENARIOS), 'sources_sha256': tested,
'scope': 'SpawnPlacements.isSpawnPositionOk (placement types, isValidSpawn, isValidEmptySpawnBlock with per-type '
'dangerous blocks) and checkSpawnRules (every registered predicate, peaceful, spawn reasons) with the '
'random draw count.'})
print(f'{len(cases):,} spawn rule cases over {len(types)} entity types match vanilla')
if __name__ == '__main__':
main()