From a21d268a41ae0d4bbd5a80fd487ad177a8016679 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:40:15 +0200 Subject: [PATCH] Spawn naturally through a NaturalSpawner port shared by the game mobs::spawn_selection ports NaturalSpawner over a NaturalLevel trait: the spawn state (category counts, spawn potential charges, local caps), the filtered categories, spawnForChunk, spawnCategoryForPosition with mobsAt, isValidSpawnPostitionForType and isValidPositionForMob, and spawnMobsForChunkGeneration. The game's spawning goes through it. Biomes now load their spawn costs and creature_world_gen_spawn_probability. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/biome.rs | 20 +- crates/horizon-client/src/collisions.rs | 17 + crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/creatures.rs | 245 ---- .../src/game/natural_spawning.rs | 364 ++++++ crates/horizon-client/src/game/structures.rs | 26 +- crates/horizon-client/src/mobs/data.rs | 16 + .../src/mobs/spawn_selection.rs | 1161 ++++++++++++++++- 8 files changed, 1557 insertions(+), 293 deletions(-) create mode 100644 crates/horizon-client/src/game/natural_spawning.rs diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 338bec1f9..e0c6900cf 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -24,6 +24,9 @@ pub struct SpawnEntry { pub struct BiomeInfo { /// `natural_mob_spawns` by category (creature, monster, ...). pub spawns: HashMap>, + /// `natural_mob_spawns` spawn costs by entity type. + pub spawn_costs: HashMap, + /// The `gameplay/creature_world_gen_spawn_probability` attribute. pub creature_probability: f32, pub name: String, pub temperature: f32, @@ -105,15 +108,26 @@ impl Biomes { _ => GrassModifier::None, }; let mut spawns: HashMap> = HashMap::new(); - let categories = &attributes["minecraft:gameplay/natural_mob_spawns"]["argument"]["spawns_by_category"]; + let natural = &attributes["minecraft:gameplay/natural_mob_spawns"]; + // A modifier object ({argument, modifier: overlay}) or the plain value; + // the overlay over the dimension's empty default is the biome's value. + let natural = if natural["argument"].is_object() { + &natural["argument"] + } else { + natural + }; + let categories = &natural["spawns_by_category"]; for (category, entries) in categories.as_object().into_iter().flatten() { let list = crate::mobs::spawn_selection::parse_entries(entries); spawns.insert(category.clone(), list); } list.push(BiomeInfo { spawns, - creature_probability: v["creature_spawn_probability"].as_f64().unwrap_or(0.1) - as f32, + spawn_costs: crate::mobs::spawn_selection::parse_costs(&natural["spawn_costs"]), + creature_probability: + attributes["minecraft:gameplay/creature_world_gen_spawn_probability"] + .as_f64() + .unwrap_or(0.1) as f32, temperature, downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 6b06c5384..a7790c283 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -78,6 +78,23 @@ impl SceneCollisions<'_, '_> { )?) } } +/// `noCollision(null, box)`: block collisions under the empty collision +/// context, as entity-less queries such as spawn checks use. +pub fn no_collision_empty(world: &mut W, bounds: Aabb) -> bool +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + no_world_collision( + world, + CollisionCheckRequest { + entity: EntityIdentity(0), + context: CollisionContext::empty(false), + bounds, + candidate_budget: 1_000_000, + }, + ) + .unwrap_or(false) +} impl BlockCollisionWorld for SceneCollisions<'_, '_> { type Error = io::Error; type Chunk = ChunkPos; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 92847eb5f..667e7d911 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -52,6 +52,7 @@ mod mount_menu; mod mounts; mod music; mod names; +mod natural_spawning; mod nautili; mod options; mod packs; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 062ce4443..0d7e34572 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3,7 +3,6 @@ //! breeding, conversions, drops), projectiles, player interactions //! (feeding, shearing, milking, spawn eggs, throwing) and rendering. use super::{Dim, Game, view_vector}; -use horizon_client::mobs::spawn_selection; use horizon_client::{ Result, blocks::Fluid, @@ -38,17 +37,6 @@ pub(super) struct Creatures { /// The wandering trader spawner's clock. pub trader: super::wandering_trader::Spawner, } -/// MobCategory caps (maxInstancesPerChunk with the 17x17 spawnable chunk area). -const CATEGORIES: [(&str, usize); 7] = [ - ("monster", 70), - ("creature", 10), - ("ambient", 15), - ("axolotls", 5), - ("underground_water_creature", 5), - ("water_creature", 5), - ("water_ambient", 20), -]; - struct ProjWorld<'a, 'w> { w: &'a MobWorld<'w>, targets: Vec<(Who, Aabb)>, @@ -356,78 +344,6 @@ impl Game<'_> { } horizon_client::chunk::MIN_Y } - /// NaturalSpawner.spawnMobsForChunkGeneration (creature packs at generation). - pub(super) fn spawn_generation_creatures(&mut self, cx: i32, cz: i32) { - let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { - return; - }; - let biome = self.res.biomes.get(chunk.biome(8, 64, 8)).clone(); - let Some(entries) = biome.spawns.get("creature").cloned() else { - return; - }; - let (xo, zo) = (cx * 16, cz * 16); - while self.world.random.next_float() < biome.creature_probability { - let Some(entry) = spawn_selection::weighted_pick(&entries, &mut self.world.random) - else { - return; - }; - let count = spawn_selection::sample_count(&entry, &mut self.world.random); - let mut x = xo + self.world.random.next_int_bound(16).unwrap_or(0); - let mut z = zo + self.world.random.next_int_bound(16).unwrap_or(0); - let (sx, sz) = (x, z); - let Some(kind) = self.res.mob_types.get(&entry.entity).cloned() else { - continue; - }; - for _ in 0..count { - let mut success = false; - let mut attempts = 0; - while !success && attempts < 4 { - attempts += 1; - let mut y = self.motion_top(x, z); - let placement = self.res.mob_data.placement(&entry.entity); - if placement == horizon_client::mobs::data::Placement::OnGround { - let below = self.world.block(x, y - 1, z); - if self.res.mob_data.state(below).flags & horizon_client::mobs::data::LAND - != 0 - { - y -= 1; - } - } - let ok = { - let w = self.mob_world_base(&[]); - spawning::placement_ok(kind.species, &w, x, y, z) && { - let mut r = self.world.random.clone(); - - spawning::spawn_rules_ok(kind.species, &w, &mut r, x, y, z) - } - }; - if ok { - let width = kind.width; - let fx = - f64::from(x).clamp(f64::from(xo) + width, f64::from(xo) + 16.0 - width); - let fz = - f64::from(z).clamp(f64::from(zo) + width, f64::from(zo) + 16.0 - width); - if self - .spawn_mob(&entry.entity, [fx, f64::from(y), fz], true) - .is_some() - { - success = true; - } - } - x += self.world.random.next_int_bound(5).unwrap_or(0) - - self.world.random.next_int_bound(5).unwrap_or(0); - z += self.world.random.next_int_bound(5).unwrap_or(0) - - self.world.random.next_int_bound(5).unwrap_or(0); - while x < xo || x >= xo + 16 || z < zo || z >= zo + 16 { - x = sx + self.world.random.next_int_bound(5).unwrap_or(0) - - self.world.random.next_int_bound(5).unwrap_or(0); - z = sz + self.world.random.next_int_bound(5).unwrap_or(0) - - self.world.random.next_int_bound(5).unwrap_or(0); - } - } - } - } - } pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> { let (rain, thunder) = self.world.weather.levels(1.0); MobWorld { @@ -496,167 +412,6 @@ impl Game<'_> { } } } - /// NaturalSpawner.spawnForChunk over the chunks within 8 of the player. - fn spawn_natural(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); - let mut counts = [0usize; 7]; - for m in &self.mobs { - if let Some(i) = CATEGORIES.iter().position(|c| c.0 == m.kind.category) { - counts[i] += 1; - } - } - let creature_tick = self.world.game_time % 400 == 0; - let mut chunks: Vec<(i32, i32)> = (-8..=8) - .flat_map(|dx| (-8..=8).map(move |dz| (pcx + dx, pcz + dz))) - .filter(|c| self.world.chunks.contains_key(c)) - .collect(); - // ChunkMap: shuffled each tick. - for i in (1..chunks.len()).rev() { - let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; - chunks.swap(i, j); - } - // ServerChunkCache.tickChunks: the chunks are shuffled every tick, but - // no category spawns without spawn_mobs, and only friendly ones - // unless the level is spawning monsters (ServerLevel.isSpawningMonsters). - let spawn_mobs = self.ui.rules.bool("spawn_mobs"); - let spawn_enemies = spawn_mobs && self.ui.rules.bool("spawn_monsters"); - for (cx, cz) in chunks { - for (ci, (category, cap)) in CATEGORIES.iter().enumerate() { - if !spawn_mobs - || counts[ci] >= *cap - || *category == "creature" && !creature_tick - || *category == "monster" && !spawn_enemies - { - continue; - } - counts[ci] += self.spawn_category_for_chunk(category, cx, cz, p); - } - } - } - /// NaturalSpawner.spawnCategoryForPosition at a random point in the chunk. - fn spawn_category_for_chunk( - &mut self, - category: &str, - cx: i32, - cz: i32, - player: Vec3, - ) -> usize { - let x0 = cx * 16 + self.world.random.next_int_bound(16).unwrap_or(0); - let z0 = cz * 16 + self.world.random.next_int_bound(16).unwrap_or(0); - let top = self.motion_top(x0, z0) + 1; - let min = horizon_client::chunk::MIN_Y; - let y = min + self.world.random.next_int_bound(top - min + 1).unwrap_or(0); - if y < min + 1 { - return 0; - } - let start = self.res.facts.get(self.world.block(x0, y, z0)); - if start.full_collision { - return 0; - } - let mut spawned = 0; - for _ in 0..3 { - let (mut x, mut z) = (x0, z0); - let mut entry: Option = None; - let mut group = (self.world.random.next_float() * 4.0).ceil() as u32; - let mut cluster = 0; - let mut i = 0; - while i < group { - i += 1; - x += self.world.random.next_int_bound(6).unwrap_or(0) - - self.world.random.next_int_bound(6).unwrap_or(0); - z += self.world.random.next_int_bound(6).unwrap_or(0) - - self.world.random.next_int_bound(6).unwrap_or(0); - let (fx, fz) = (f64::from(x) + 0.5, f64::from(z) + 0.5); - let d2 = (fx - player.x).powi(2) - + (f64::from(y) - player.y).powi(2) - + (fz - player.z).powi(2); - if d2 <= 576.0 { - continue; - } - if entry.is_none() { - let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { - break; - }; - let biome = self.res.biomes.get(chunk.biome(x, y, z)).clone(); - let list = self.spawn_list(category, [x, y, z], &biome.spawns); - let reduced = self - .res - .mob_data - .biome_tags - .get("minecraft:reduced_water_ambient_spawns") - .is_some_and(|t| t.contains(&biome.name)); - let Some(e) = spawn_selection::random_spawn_mob_at( - &list, - category, - reduced, - &mut self.world.random, - ) else { - break; - }; - group = spawn_selection::sample_count(&e, &mut self.world.random); - entry = Some(e); - } - let e = entry.clone().unwrap_or_else(|| unreachable!()); - let despawn = if category == "water_ambient" { - 64.0 - } else { - 128.0 - }; - if d2 > despawn * despawn { - continue; - } - let Some(kind) = self.res.mob_types.get(&e.entity).cloned() else { - break; - }; - let ok = { - let w = self.mob_world_base(&[]); - let mut r = self.world.random.clone(); - let placed = spawning::placement_ok(kind.species, &w, x, y, z) - && spawning::spawn_rules_ok(kind.species, &w, &mut r, x, y, z); - let half = kind.width / 2.0; - let room = w.no_collision(Aabb::new( - Vec3::new(fx - half, f64::from(y), fz - half), - Vec3::new(fx + half, f64::from(y) + kind.height, fz + half), - )); - // PathfinderMob.checkSpawnRules: walk target value >= 0 (monsters need darkness). - let light_ok = !kind.category.eq("monster") - || matches!( - kind.species, - Species::Slime - | Species::SulfurCube - | Species::Ghast - | Species::MagmaCube - | Species::Guardian - | Species::ElderGuardian - ) - || w.brightness(x, y, z) <= 0.5; - let consumed = r; - (placed && room && light_ok, consumed) - }; - self.world.random = ok.1; - if !ok.0 { - continue; - } - if d2 > 16384.0 && kind.category != "creature" { - continue; - } - if self - .spawn_mob(&e.entity, [fx, f64::from(y), fz], false) - .is_some() - { - cluster += 1; - spawned += 1; - if spawned >= 4 || cluster >= group.max(1) { - return spawned; - } - } - } - } - spawned - } /// Advance every mob one tick, then apply their events. pub(super) fn tick_creatures(&mut self) -> Result<()> { self.attack_ticks = self.attack_ticks.saturating_add(1); diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs new file mode 100644 index 000000000..34e346f33 --- /dev/null +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -0,0 +1,364 @@ +//! The game's side of `NaturalSpawner` (`mobs::spawn_selection`): the level +//! it reads, the spawning chunks and caps of `ServerChunkCache.tickChunks`, +//! and the mobs it adds (finalized with the game's `finalizeSpawn`). +use super::{Dim, Game}; +use horizon_client::{ + biome::{BiomeInfo, SpawnEntry}, + blocks::BlockFacts, + collisions::{SceneCollisions, no_collision_empty}, + mobs::{ + Mob, MobWorld, Species, + data::{self, MobData}, + spawn_rules::{Dimension, SpawnLevel}, + spawn_selection::{ + self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest, + SpawnState, Spawned, StructureAt, StructureSpawns, + }, + }, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource, WorldgenRandom}, +}; +use horizon_world::registry::BlockStateId; +use std::collections::HashMap; + +/// The game level as natural spawning reads it. +struct GameLevel<'g, 'a> { + game: &'g Game<'a>, + w: MobWorld<'g>, +} +impl GameLevel<'_, '_> { + fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { + let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; + Some(self.game.res.biomes.get(chunk.biome(x, y, z))) + } +} +impl SpawnLevel for GameLevel<'_, '_> { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.w.state(x, y, z) + } + fn facts(&self) -> &BlockFacts { + self.w.facts + } + fn mob_data(&self) -> &MobData { + self.w.data + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.w.block_tag(tag, block) + } + fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool { + self.w.biome_tag(tag, x, y, z) + } + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 { + self.w.sky_light(x, y, z) + } + fn block_light(&self, x: i32, y: i32, z: i32) -> i32 { + self.w.block_light(x, y, z) + } + fn sky_darken(&self) -> i32 { + SpawnLevel::sky_darken(&self.w) + } + fn thundering(&self) -> bool { + self.w.thundering + } + fn sea_level(&self) -> i32 { + self.w.sea_level() + } + fn world_surface(&self, x: i32, z: i32) -> i32 { + self.w.world_surface(x, z) + } + fn peaceful(&self) -> bool { + self.w.peaceful() + } + fn dimension(&self) -> Dimension { + self.w.dimension() + } + fn surface_slime_chance(&self, x: i32, y: i32, z: i32) -> f32 { + self.w.surface_slime_chance(x, y, z) + } + fn world_seed(&self) -> i64 { + self.w.world_seed + } + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { + self.w.player_near(x, y, z, distance) + } +} +impl NaturalLevel for GameLevel<'_, '_> { + fn min_y(&self) -> i32 { + horizon_client::chunk::MIN_Y + } + fn max_y(&self) -> i32 { + horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT - 1 + } + fn ambient_light(&self) -> f32 { + match self.game.dim { + Dim::Nether => 0.1, + Dim::End => 0.25, + _ => 0.0, + } + } + fn has_ceiling(&self) -> bool { + self.game.dim == Dim::Nether + } + fn mob_type(&self, entity: &str) -> Option<(Species, f32, f32, Category)> { + let t = self.game.res.mob_types.get(entity)?; + Some(( + t.species, + t.width as f32, + t.height as f32, + Category::from_name(&t.category), + )) + } + fn biome_spawns(&self, x: i32, y: i32, z: i32) -> Option<&HashMap>> { + self.biome(x, y, z).map(|b| &b.spawns) + } + fn spawn_cost(&self, entity: &str, x: i32, y: i32, z: i32) -> Option { + self.biome(x, y, z)?.spawn_costs.get(entity).copied() + } + fn creature_probability(&self, x: i32, y: i32, z: i32) -> f32 { + self.biome(x, y, z).map_or(0.1, |b| b.creature_probability) + } + fn structures_at(&self, x: i32, y: i32, z: i32) -> Vec { + self.game + .structures_reaching([x, y, z]) + .into_iter() + .map(|(id, in_piece)| StructureAt { + id, + in_piece, + in_bounds: true, + }) + .collect() + } + fn structure_spawns(&self) -> &StructureSpawns { + StructureSpawns::shared(&self.game.options.resources) + } + fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option { + let p = self.game.player.as_ref()?; + if self.game.spectator() { + return None; + } + let d = [p.position.x - x, p.position.y - y, p.position.z - z]; + Some(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) + } + fn respawn(&self) -> Option<[i32; 3]> { + // The world spawn point lives in the overworld. + if self.game.dim != Dim::Overworld { + return None; + } + self.game.level.spawn.map(|s| { + [ + s[0].floor() as i32, + s[1].floor() as i32, + s[2].floor() as i32, + ] + }) + } + fn can_spawn_in_chunk(&self, cx: i32, cz: i32) -> bool { + self.game.world.chunks.contains_key(&(cx, cz)) + } + fn no_collision(&self, bounds: Aabb) -> bool { + let mut scene = SceneCollisions { + world: &self.game.world, + binding: self.w.collision, + }; + no_collision_empty(&mut scene, bounds) + } + fn unobstructed(&self, bounds: Aabb) -> bool { + let player = self + .game + .player_view() + .is_some_and(|p| p.alive && !p.spectator && p.bounds.intersects(bounds)); + !player + && !self + .game + .mobs + .iter() + .any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds)) + } + fn spawn_mobs(&self) -> bool { + self.game.ui.rules.bool("spawn_mobs") + } + fn heightmap(&self, kind: Heightmap, x: i32, z: i32) -> i32 { + let top = horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT; + (horizon_client::chunk::MIN_Y..top) + .rev() + .find(|&y| heightmap_blocks(self.w.facts, self.w.data, kind, self.state(x, y, z))) + .map_or(horizon_client::chunk::MIN_Y, |y| y + 1) + } + fn pathfindable_land(&self, x: i32, y: i32, z: i32) -> bool { + self.w.data.state(self.state(x, y, z)).flags & data::LAND != 0 + } +} +/// `Heightmap.Types` predicates: WORLD_SURFACE (not air), OCEAN_FLOOR +/// (`blocksMotion`), MOTION_BLOCKING (or a fluid) and NO_LEAVES. +pub fn heightmap_blocks( + facts: &BlockFacts, + data: &MobData, + kind: Heightmap, + state: BlockStateId, +) -> bool { + let f = facts.get(state); + let blocks_motion = data.state(state).flags & data::SOLID != 0 + && &*f.name != "minecraft:cobweb" + && &*f.name != "minecraft:bamboo_sapling"; + let fluid = f.fluid != horizon_client::blocks::Fluid::None; + match kind { + Heightmap::WorldSurface => !facts.is_air(state), + Heightmap::OceanFloor => blocks_motion, + Heightmap::MotionBlocking => blocks_motion || fluid, + Heightmap::MotionBlockingNoLeaves => { + (blocks_motion || fluid) && !f.name.ends_with("_leaves") + } + } +} + +impl<'a> Game<'a> { + fn natural_level(&self) -> GameLevel<'_, 'a> { + GameLevel { + game: self, + w: self.mob_world_base(&[]), + } + } + /// Creates a mob the spawner accepted, finalized the game's way; the + /// caller adds it with [`Game::add_spawned`]. + fn finalize_spawned(&self, r: &SpawnRequest, pending: &mut Vec) -> Option { + let kind = self.res.mob_types.get(r.entity)?.clone(); + let [x, y, z] = r.position; + let mut mob = Mob::new(0, kind, Vec3::new(x, y, z), r.yaw); + let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32); + let difficulty = self.local_difficulty(r.position); + horizon_client::mobs::spawning::finalize(&mut mob, &facts, &difficulty); + horizon_client::mobs::raider::finalize( + &mut mob, + horizon_client::mobs::raider::Reason::Natural, + ); + let bounds = mob.bounds(); + pending.push(mob); + Some(Spawned { + bounds, + school: true, + }) + } + /// Adds the mobs a spawn pass created: ids, enchanted gear and jockeys. + fn add_spawned(&mut self, pending: Vec, persistent: bool) { + for mut mob in pending { + self.next_entity += 1; + mob.id = self.next_entity; + mob.persistent = persistent; + let id = mob.id; + self.mobs.push(mob); + self.enchant_spawn_equipment(id); + if !persistent { + self.spawn_jockeys(id, true); + } + } + } + /// `ServerChunkCache.tickChunks`: the spawn state over the loaded mobs, + /// the categories under their global caps (creatures every 400 ticks), + /// then `spawnForChunk` in the shuffled chunks within 128 blocks of the + /// player. + pub(super) fn spawn_natural(&mut self) { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); + // ChunkMap.collectSpawningChunks: tracked chunks whose centre is + // within 128 blocks of a non-spectator. + let spectator = self.spectator(); + let mut chunks: Vec<(i32, i32)> = (-8..=8) + .flat_map(|dx| (-8..=8).map(move |dz| (pcx + dx, pcz + dz))) + .filter(|&(cx, cz)| { + let (x, z) = (f64::from(cx * 16 + 8) - p.x, f64::from(cz * 16 + 8) - p.z); + !spectator && x * x + z * z < 16384.0 && self.world.chunks.contains_key(&(cx, cz)) + }) + .collect(); + let spawn_mobs = self.ui.rules.bool("spawn_mobs"); + let spawn_enemies = self.ui.rules.bool("spawn_monsters"); + let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); + let mut pending = Vec::new(); + { + let level = self.natural_level(); + let counted: Vec = self + .mobs + .iter() + .map(|m| Counted { + entity: &m.kind.id, + category: Category::from_name(&m.kind.category), + block: [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ], + is_mob: true, + persistent: m.persistent, + }) + .collect(); + let players = vec![SpawnPlayer { + position: [p.x, p.y, p.z], + spectator, + }]; + // A single player's natural spawn chunk tracker covers 17 x 17 chunks. + let mut state = SpawnState::new(&level, 289, players, &counted, |cx, cz| { + self.world.chunks.contains_key(&(cx, cz)) + }); + let categories = if spawn_mobs { + state.filtered_categories(spawn_enemies, self.world.game_time % 400 == 0) + } else { + Vec::new() + }; + // Util.shuffle. + for i in (1..chunks.len()).rev() { + let j = random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; + chunks.swap(i, j); + } + if !categories.is_empty() { + for chunk in chunks { + let mut spawn = + |l: &GameLevel, r: &SpawnRequest| l.game.finalize_spawned(r, &mut pending); + spawn_selection::spawn_for_chunk( + &level, + &mut random, + &mut state, + &categories, + chunk, + &mut spawn, + &mut |_| {}, + ); + } + } + } + self.world.random = random; + self.add_spawned(pending, false); + } + /// `NoiseBasedChunkGenerator.spawnOriginalMobs`: creature packs for a + /// freshly generated chunk, from the biome at its corner column's top, + /// with the chunk's decoration-seeded random (mobs are not generated in + /// the End). + pub(super) fn spawn_generation_creatures(&mut self, cx: i32, cz: i32) { + if !self.world.chunks.contains_key(&(cx, cz)) || self.dim == Dim::End { + return; + } + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_decoration_seed(self.level.seed, cx * 16, cz * 16); + // The region's own random: no creature's spawn predicate draws from it. + let mut rules = LegacyRandom::new(self.level.seed ^ (i64::from(cx) << 32 | i64::from(cz))); + let mut pending = Vec::new(); + { + let level = self.natural_level(); + let source = [cx * 16, level.max_y(), cz * 16]; + let mut spawn = + |l: &GameLevel, r: &SpawnRequest| l.game.finalize_spawned(r, &mut pending); + spawn_selection::spawn_mobs_for_chunk_generation( + &level, + source, + (cx, cz), + &mut random, + &mut rules, + &mut spawn, + &mut |_| {}, + ); + } + self.add_spawned(pending, true); + } +} diff --git a/crates/horizon-client/src/game/structures.rs b/crates/horizon-client/src/game/structures.rs index 1b2199d4d..e941f2fd9 100644 --- a/crates/horizon-client/src/game/structures.rs +++ b/crates/horizon-client/src/game/structures.rs @@ -6,7 +6,7 @@ use super::Game; impl Game<'_> { /// Structures reaching `pos`: (id, inside a piece). `getStructureAt` /// tests the start's whole box, `getStructureWithPieceAt` a piece's. - fn structures_reaching(&self, pos: [i32; 3]) -> Vec<(String, bool)> { + pub(super) fn structures_reaching(&self, pos: [i32; 3]) -> Vec<(String, bool)> { let Some(chunk) = self.world.chunks.get(&(pos[0] >> 4, pos[2] >> 4)) else { return Vec::new(); }; @@ -39,28 +39,4 @@ impl Game<'_> { .map(|(n, _)| n) .collect() } - /// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, the - /// structure `spawn_overrides` whose box (or piece) holds `pos`, else the - /// biome's list. - pub(super) fn spawn_list( - &self, - category: &str, - pos: [i32; 3], - biome: &std::collections::HashMap>, - ) -> Vec { - use horizon_client::mobs::spawn_selection::{StructureAt, StructureSpawns, mobs_at}; - let structures: Vec = self - .structures_reaching(pos) - .into_iter() - .map(|(id, in_piece)| StructureAt { - id, - in_piece, - in_bounds: true, - }) - .collect(); - let below = self.world.block(pos[0], pos[1] - 1, pos[2]); - let bricks = &*self.res.facts.get(below).name == "minecraft:nether_bricks"; - let spawns = StructureSpawns::shared(&self.options.resources); - mobs_at(spawns, biome, category, &structures, bricks) - } } diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index dc9e391aa..48fc4234f 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -43,6 +43,8 @@ pub enum Placement { pub struct MobData { pub states: Vec, pub placements: HashMap, + /// Each entity type's `SpawnPlacements.getHeightmapType`. + pub heightmaps: HashMap, pub animations: HashMap, /// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id. pub biome_tags: HashMap>, @@ -109,6 +111,12 @@ impl MobData { (k.clone(), placement) }) .collect(); + let heightmaps = v["placements"] + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, p)| Some((k.clone(), p["heightmap"].as_str()?.to_owned()))) + .collect(); let animations = v["animations"] .as_object() .into_iter() @@ -118,6 +126,7 @@ impl MobData { Self { states, placements, + heightmaps, animations, biome_tags: HashMap::new(), entity_tags: HashMap::new(), @@ -171,6 +180,7 @@ impl MobData { Self { states, placements: HashMap::new(), + heightmaps: HashMap::new(), animations: HashMap::new(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), @@ -186,6 +196,12 @@ impl MobData { top: 1.0, }) } + /// `SpawnPlacements.getHeightmapType` (MOTION_BLOCKING_NO_LEAVES unless registered). + pub fn heightmap(&self, entity: &str) -> &str { + self.heightmaps + .get(entity) + .map_or("MOTION_BLOCKING_NO_LEAVES", String::as_str) + } pub fn placement(&self, entity: &str) -> Placement { self.placements .get(entity) diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index fba1cb8fa..0e6f777a0 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -1,9 +1,24 @@ -//! `NaturalSpawner.getRandomSpawnMobAt` and `mobsAt`: which spawn list a -//! position uses (the nether fortress bounds, then structure spawn overrides -//! by piece or bounding box, then the biome's natural mob spawns), the -//! reduced water ambient odds, the weighted pick and the group size sample. +//! `NaturalSpawner`: which mob spawns where and when. The spawn state +//! (`createState`: category counts, the spawn potential's charges, the +//! per-player local caps), the filtered categories and their global and local +//! caps, `spawnForChunk` and `spawnCategoryForPosition` (the three packs of up +//! to four attempts, the distance and respawn checks, `getRandomSpawnMobAt` +//! over `mobsAt`: the nether fortress bounds, structure spawn overrides by +//! piece or bounding box, then the biome's natural mob spawns), the per-type +//! checks of `isValidSpawnPostitionForType` and `isValidPositionForMob` +//! (each class's `checkSpawnRules` walk target value, `checkSpawnObstruction`, +//! `removeWhenFarAway`, cluster and group sizes), and +//! `spawnMobsForChunkGeneration`. Everything reads the level through +//! [`NaturalLevel`] so the game and the differential test world +//! (tools/test_natural_spawn_parity.py) run the same code; random draws follow +//! vanilla's order. +use super::Species; +use super::spawn_rules::{self, Reason, SpawnLevel}; use crate::biome::SpawnEntry; -use horizon_core::random::RandomSource; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -39,6 +54,529 @@ pub fn parse_entries(list: &Value) -> Vec { }) .collect() } +/// `MobSpawnSettings.MobSpawnCost`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SpawnCost { + pub energy_budget: f64, + pub charge: f64, +} +/// The `spawn_costs` of a `natural_mob_spawns` value. +pub fn parse_costs(costs: &Value) -> HashMap { + costs + .as_object() + .into_iter() + .flatten() + .map(|(k, c)| { + ( + k.clone(), + SpawnCost { + energy_budget: c["energy_budget"].as_f64().unwrap_or(0.0), + charge: c["charge"].as_f64().unwrap_or(0.0), + }, + ) + }) + .collect() +} + +/// `MobCategory`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Category { + Monster, + Creature, + Ambient, + Axolotls, + UndergroundWaterCreature, + WaterCreature, + WaterAmbient, + Misc, +} +impl Category { + pub const ALL: [Self; 8] = [ + Self::Monster, + Self::Creature, + Self::Ambient, + Self::Axolotls, + Self::UndergroundWaterCreature, + Self::WaterCreature, + Self::WaterAmbient, + Self::Misc, + ]; + /// `NaturalSpawner.SPAWNING_CATEGORIES`: all but MISC, in enum order. + pub const SPAWNING: [Self; 7] = [ + Self::Monster, + Self::Creature, + Self::Ambient, + Self::Axolotls, + Self::UndergroundWaterCreature, + Self::WaterCreature, + Self::WaterAmbient, + ]; + pub fn name(self) -> &'static str { + match self { + Self::Monster => "monster", + Self::Creature => "creature", + Self::Ambient => "ambient", + Self::Axolotls => "axolotls", + Self::UndergroundWaterCreature => "underground_water_creature", + Self::WaterCreature => "water_creature", + Self::WaterAmbient => "water_ambient", + Self::Misc => "misc", + } + } + pub fn from_name(name: &str) -> Self { + Self::ALL + .into_iter() + .find(|c| c.name() == name) + .unwrap_or(Self::Misc) + } + fn index(self) -> usize { + self as usize + } + /// `getMaxInstancesPerChunk`. + pub fn max(self) -> i32 { + match self { + Self::Monster => 70, + Self::Creature => 10, + Self::Ambient => 15, + Self::Axolotls | Self::UndergroundWaterCreature | Self::WaterCreature => 5, + Self::WaterAmbient => 20, + Self::Misc => -1, + } + } + pub fn friendly(self) -> bool { + self != Self::Monster + } + pub fn persistent(self) -> bool { + matches!(self, Self::Creature | Self::Misc) + } + pub fn despawn_distance(self) -> i32 { + if self == Self::WaterAmbient { 64 } else { 128 } + } +} + +/// `PathfinderMob.checkSpawnRules`: the class's `getWalkTargetValue` at the +/// spawn position must not be negative (plain `Mob`s accept any position). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WalkTarget { + NotPathfinder, + Zero, + Animal, + Mooshroom, + Turtle, + Monster, + Giant, + Guardian, + Silverfish, + Strider, + Hoglin, + Bee, + HappyGhast, +} +fn walk_target(s: Species) -> WalkTarget { + use Species as S; + use WalkTarget as W; + match s { + S::Bat | S::Slime | S::MagmaCube | S::SulfurCube | S::Ghast | S::Phantom => { + W::NotPathfinder + } + // Monster subclasses that override it with 0. + S::Enderman | S::Creaking | S::Pillager | S::Warden => W::Zero, + S::Giant => W::Giant, + S::Guardian | S::ElderGuardian => W::Guardian, + S::Silverfish => W::Silverfish, + S::Zombie + | S::Husk + | S::Drowned + | S::ZombieVillager + | S::ZombifiedPiglin + | S::Skeleton + | S::Stray + | S::Bogged + | S::Parched + | S::WitherSkeleton + | S::Creeper + | S::Spider + | S::CaveSpider + | S::Endermite + | S::Witch + | S::Vindicator + | S::Evoker + | S::Illusioner + | S::Ravager + | S::Piglin + | S::PiglinBrute + | S::Zoglin + | S::Blaze + | S::Vex + | S::Breeze + | S::Wither => W::Monster, + S::Mooshroom => W::Mooshroom, + S::Turtle => W::Turtle, + S::Strider => W::Strider, + S::Hoglin => W::Hoglin, + S::Bee => W::Bee, + S::HappyGhast => W::HappyGhast, + // Animal subclasses with their own value. + S::Axolotl | S::Nautilus | S::ZombieNautilus => W::Zero, + S::Pig + | S::Cow + | S::Sheep + | S::Chicken + | S::Rabbit + | S::Horse + | S::Donkey + | S::Mule + | S::Llama + | S::TraderLlama + | S::SkeletonHorse + | S::ZombieHorse + | S::Camel + | S::CamelHusk + | S::Goat + | S::Panda + | S::PolarBear + | S::Fox + | S::Wolf + | S::Cat + | S::Ocelot + | S::Parrot + | S::Armadillo + | S::Frog + | S::Sniffer => W::Animal, + // Other PathfinderMobs: water animals, golems, villagers, allays... + _ => W::Zero, + } +} +/// Each class's `checkSpawnObstruction`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Obstruction { + /// `Mob`: no liquid in the box and no entity blocking it. + NoLiquidUnobstructed, + Unobstructed, + Ocelot, + NoLiquid, +} +fn obstruction(s: Species) -> Obstruction { + use Species as S; + match s { + S::Squid + | S::GlowSquid + | S::Dolphin + | S::Axolotl + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Tadpole + | S::Nautilus + | S::ZombieNautilus + | S::Guardian + | S::ElderGuardian + | S::Strider + | S::Drowned => Obstruction::Unobstructed, + S::Ocelot => Obstruction::Ocelot, + S::Ravager => Obstruction::NoLiquid, + // ZombifiedPiglin's override is the Mob default's two tests; iron + // golems and wardens never spawn naturally. + _ => Obstruction::NoLiquidUnobstructed, + } +} +/// `Mob.removeWhenFarAway` of a freshly created mob. +fn removed_when_far(s: Species) -> bool { + use Species as S; + match s { + // Animal, golems, villagers, traders, allays and wardens never; + // cats and ocelots only past 2400 ticks; chickens as jockeys. + S::Axolotl + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Tadpole + | S::CamelHusk + | S::ZombieHorse + | S::Hoglin + | S::Nautilus + | S::ZombieNautilus => true, + S::Villager + | S::WanderingTrader + | S::IronGolem + | S::SnowGolem + | S::Shulker + | S::Allay + | S::Warden => false, + _ => !is_animal(s), + } +} +fn is_animal(s: Species) -> bool { + use Species as S; + matches!(walk_target(s), WalkTarget::Animal) + || matches!( + s, + S::Axolotl + | S::Nautilus + | S::ZombieNautilus + | S::Mooshroom + | S::Turtle + | S::Strider + | S::Hoglin + | S::Bee + | S::HappyGhast + ) +} +/// `Mob.getMaxSpawnClusterSize`. +pub fn max_cluster_size(s: Species) -> u32 { + use Species as S; + match s { + S::Horse + | S::Donkey + | S::Mule + | S::Llama + | S::TraderLlama + | S::SkeletonHorse + | S::ZombieHorse + | S::Camel + | S::CamelHusk => 6, + S::Cod | S::TropicalFish | S::Pufferfish | S::Tadpole | S::Wolf => 8, + S::Salmon => 5, + S::Ghast | S::HappyGhast | S::Pillager => 1, + _ => 4, + } +} +/// `EntityType.canSpawnFarFromPlayer`: creatures, misc, pillagers, shulkers. +fn spawns_far_from_player(s: Species, category: Category) -> bool { + matches!(category, Category::Creature | Category::Misc) + || matches!(s, Species::Pillager | Species::Shulker) +} + +/// What natural spawning reads from a level beyond the spawn rules. +pub trait NaturalLevel: SpawnLevel { + fn min_y(&self) -> i32; + /// `getMaxY()`: the highest buildable block. + fn max_y(&self) -> i32; + /// `DimensionType.ambientLight`. + fn ambient_light(&self) -> f32; + fn has_ceiling(&self) -> bool; + /// The entity type's species, width, height and category. + fn mob_type(&self, entity: &str) -> Option<(Species, f32, f32, Category)>; + /// The `natural_mob_spawns` lists by category at a position. + fn biome_spawns(&self, x: i32, y: i32, z: i32) -> Option<&HashMap>>; + /// The `natural_mob_spawns` spawn cost of a type at a position. + fn spawn_cost(&self, entity: &str, x: i32, y: i32, z: i32) -> Option; + /// The `creature_world_gen_spawn_probability` attribute at a position. + fn creature_probability(&self, x: i32, y: i32, z: i32) -> f32; + /// Every structure whose references reach the position's chunk, in the + /// chunk's reference order. + fn structures_at(&self, x: i32, y: i32, z: i32) -> Vec; + fn structure_spawns(&self) -> &StructureSpawns; + /// `getNearestPlayer(x, y, z, -1, false)`: the squared distance to the + /// nearest player that is not a spectator. + fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option; + /// The world spawn point, when it is in this dimension. + fn respawn(&self) -> Option<[i32; 3]>; + /// `ServerLevel.canSpawnEntitiesInChunk`. + fn can_spawn_in_chunk(&self, cx: i32, cz: i32) -> bool; + /// `noCollision(null, box)`: blocks under an empty collision context and + /// entities that can be collided with. + fn no_collision(&self, bounds: Aabb) -> bool; + /// `isUnobstructed(entity)`: no entity blocking building overlaps. + fn unobstructed(&self, bounds: Aabb) -> bool; + /// The `spawn_mobs` game rule. + fn spawn_mobs(&self) -> bool; + /// `getHeight(heightmap, x, z)`. + fn heightmap(&self, kind: Heightmap, x: i32, z: i32) -> i32; + /// `isPathfindable(PathComputationType.LAND)` of the block. + fn pathfindable_land(&self, x: i32, y: i32, z: i32) -> bool; +} + +/// The heightmap types `SpawnPlacements` registers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Heightmap { + WorldSurface, + OceanFloor, + MotionBlocking, + MotionBlockingNoLeaves, +} +impl Heightmap { + pub fn from_name(name: &str) -> Self { + match name { + "WORLD_SURFACE" => Self::WorldSurface, + "OCEAN_FLOOR" => Self::OceanFloor, + "MOTION_BLOCKING" => Self::MotionBlocking, + _ => Self::MotionBlockingNoLeaves, + } + } +} + +/// `LevelReader.getLightLevelDependentMagicValue`. +fn magic_light(l: &L, x: i32, y: i32, z: i32) -> f32 { + let raw = l + .block_light(x, y, z) + .max(l.sky_light(x, y, z) - l.sky_darken()); + let v = raw as f32 / 15.0; + let curved = v / (4.0 - 3.0 * v); + curved + l.ambient_light() * (1.0 - curved) +} +fn cost_from_light(l: &L, x: i32, y: i32, z: i32) -> f32 { + magic_light(l, x, y, z) - 0.5 +} +fn name_at(l: &L, x: i32, y: i32, z: i32) -> &str { + &l.facts().get(l.state(x, y, z)).name +} +fn fluid_at(l: &L, x: i32, y: i32, z: i32) -> crate::blocks::Fluid { + l.facts().get(l.state(x, y, z)).fluid +} +/// `checkSpawnRules(level, NATURAL)` of a freshly created mob at a block. +fn mob_spawn_rules(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + use crate::blocks::Fluid; + let value = match walk_target(s) { + WalkTarget::NotPathfinder | WalkTarget::Zero => 0.0, + WalkTarget::Animal => { + if name_at(l, x, y - 1, z) == "minecraft:grass_block" { + 10.0 + } else { + cost_from_light(l, x, y, z) + } + } + WalkTarget::Mooshroom => { + if name_at(l, x, y - 1, z) == "minecraft:mycelium" { + 10.0 + } else { + cost_from_light(l, x, y, z) + } + } + WalkTarget::Turtle => { + if fluid_at(l, x, y, z) == Fluid::Water + || l.block_tag("minecraft:sand", name_at(l, x, y - 1, z)) + { + 10.0 + } else { + cost_from_light(l, x, y, z) + } + } + WalkTarget::Monster => -cost_from_light(l, x, y, z), + WalkTarget::Giant => cost_from_light(l, x, y, z), + WalkTarget::Guardian => { + if fluid_at(l, x, y, z) == Fluid::Water { + 10.0 + cost_from_light(l, x, y, z) + } else { + -cost_from_light(l, x, y, z) + } + } + WalkTarget::Silverfish => { + if infested_host(name_at(l, x, y - 1, z)) { + 10.0 + } else { + -cost_from_light(l, x, y, z) + } + } + // A new strider is not in lava yet. + WalkTarget::Strider => { + if fluid_at(l, x, y, z) == Fluid::Lava { + 10.0 + } else { + 0.0 + } + } + // A new hoglin remembers no repellent. + WalkTarget::Hoglin => { + if name_at(l, x, y - 1, z) == "minecraft:crimson_nylium" { + 10.0 + } else { + 0.0 + } + } + WalkTarget::Bee => { + if l.facts().is_air(l.state(x, y, z)) { + 10.0 + } else { + 0.0 + } + } + WalkTarget::HappyGhast => { + let air = |dy| l.facts().is_air(l.state(x, y + dy, z)); + if !air(0) { + 0.0 + } else if air(-1) && !air(-2) { + 10.0 + } else { + 5.0 + } + } + }; + value >= 0.0 +} +/// `InfestedBlock.isCompatibleHostBlock`. +fn infested_host(block: &str) -> bool { + matches!( + block, + "minecraft:stone" + | "minecraft:cobblestone" + | "minecraft:stone_bricks" + | "minecraft:mossy_stone_bricks" + | "minecraft:cracked_stone_bricks" + | "minecraft:chiseled_stone_bricks" + | "minecraft:deepslate" + ) +} +/// `LevelReader.containsAnyLiquid`: the blocks from the box's minimum corner +/// to the block holding its maximum corner. +pub fn contains_any_liquid(l: &L, b: Aabb) -> bool { + let (lo, hi) = (b.min_position(), b.max_position()); + let (x0, y0, z0) = ( + lo.x.floor() as i32, + lo.y.floor() as i32, + lo.z.floor() as i32, + ); + let (x1, y1, z1) = ( + hi.x.floor() as i32, + hi.y.floor() as i32, + hi.z.floor() as i32, + ); + (x0..=x1).any(|x| { + (y0..=y1).any(|y| { + (z0..=z1).any(|z| l.facts().get(l.state(x, y, z)).fluid != crate::blocks::Fluid::None) + }) + }) +} +/// `EntityDimensions.makeBoundingBox`: the half width is a float. +pub fn spawn_box(x: f64, y: f64, z: f64, width: f32, height: f32) -> Aabb { + let half = f64::from(width / 2.0); + Aabb::new( + Vec3::new(x - half, y, z - half), + Vec3::new(x + half, y + f64::from(height), z + half), + ) +} +/// `checkSpawnObstruction` of a freshly created mob with the given box. +fn spawn_obstruction( + s: Species, + l: &L, + bounds: Aabb, + spawned: &[Aabb], + x: i32, + y: i32, + z: i32, +) -> bool { + let unobstructed = + |l: &L| l.unobstructed(bounds) && !spawned.iter().any(|b| b.intersects(bounds)); + match obstruction(s) { + Obstruction::NoLiquidUnobstructed => !contains_any_liquid(l, bounds) && unobstructed(l), + Obstruction::Unobstructed => unobstructed(l), + Obstruction::NoLiquid => !contains_any_liquid(l, bounds), + Obstruction::Ocelot => { + if unobstructed(l) && !contains_any_liquid(l, bounds) { + if y < l.sea_level() { + return false; + } + let below = name_at(l, x, y - 1, z); + if below == "minecraft:grass_block" || l.block_tag("minecraft:leaves", below) { + return true; + } + } + false + } + } +} /// A structure's spawn override for one category. #[derive(Clone, Debug)] @@ -97,7 +635,7 @@ impl StructureSpawns { } } -/// A structure whose references reach a position. +/// A structure whose references reach a position's chunk. #[derive(Clone, Debug)] pub struct StructureAt { pub id: String, @@ -125,32 +663,36 @@ pub fn fortress_enemies() -> Vec { ] } -/// `NaturalSpawner.mobsAt`. -pub fn mobs_at( - spawns: &StructureSpawns, - biome: &HashMap>, - category: &str, - structures: &[StructureAt], - below_nether_bricks: bool, +/// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, then +/// `ChunkGenerator.getMobsAt` (the first referenced structure whose override +/// for the category holds the position), else the biome's list. +pub fn mobs_at( + l: &L, + category: Category, + x: i32, + y: i32, + z: i32, ) -> Vec { - // isInNetherFortressBounds. - if category == "monster" - && below_nether_bricks + let structures = l.structures_at(x, y, z); + if category == Category::Monster + && name_at(l, x, y - 1, z) == "minecraft:nether_bricks" && structures .iter() .any(|s| s.id == "minecraft:fortress" && s.in_bounds) { return fortress_enemies(); } - // ChunkGenerator.getMobsAt: the first structure whose override holds. - for s in structures { - if let Some(o) = spawns.get(&s.id, category) + for s in &structures { + if let Some(o) = l.structure_spawns().get(&s.id, category.name()) && (if o.piece { s.in_piece } else { s.in_bounds }) { return o.spawns.clone(); } } - biome.get(category).cloned().unwrap_or_default() + l.biome_spawns(x, y, z) + .and_then(|b| b.get(category.name())) + .cloned() + .unwrap_or_default() } /// `WeightedList.getRandom`. @@ -191,3 +733,582 @@ pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 { entry.min + random.next_int_bound(span).unwrap_or(0) as u32 } } +/// `SpawnerData.equals`: the type and the count provider (the weight is not +/// part of it; a constant and a one-value uniform differ). +fn same_spawner(a: &SpawnEntry, b: &SpawnEntry) -> bool { + a.entity == b.entity && a.constant == b.constant && a.min == b.min && a.max == b.max +} + +/// An entity counted by `NaturalSpawner.createState`. +#[derive(Clone, Debug)] +pub struct Counted<'a> { + pub entity: &'a str, + pub category: Category, + /// `blockPosition()`. + pub block: [i32; 3], + pub is_mob: bool, + /// `isPersistenceRequired() || requiresCustomPersistence()`. + pub persistent: bool, +} +/// A player as the spawn caps see it. +#[derive(Clone, Copy, Debug)] +pub struct SpawnPlayer { + pub position: [f64; 3], + pub spectator: bool, +} + +/// `NaturalSpawner.SpawnState` with its `PotentialCalculator` and +/// `LocalMobCapCalculator`. +#[derive(Clone, Debug)] +pub struct SpawnState { + spawnable_chunks: i32, + counts: [i32; 8], + charges: Vec<([i32; 3], f64)>, + players: Vec, + players_near: HashMap<(i32, i32), Vec>, + player_counts: HashMap, + last_checked: Option<([i32; 3], String, f64)>, +} +impl SpawnState { + /// `NaturalSpawner.createState`: every non-persistent entity of a + /// spawning category in a loaded chunk adds its biome's spawn charge, its + /// category count and (for mobs) the local caps of the players near it. + pub fn new( + l: &L, + spawnable_chunks: i32, + players: Vec, + entities: &[Counted], + chunk_loaded: impl Fn(i32, i32) -> bool, + ) -> Self { + let mut state = Self { + spawnable_chunks, + counts: [0; 8], + charges: Vec::new(), + players, + players_near: HashMap::new(), + player_counts: HashMap::new(), + last_checked: None, + }; + for e in entities { + if e.is_mob && e.persistent || e.category == Category::Misc { + continue; + } + let [x, y, z] = e.block; + if !chunk_loaded(x >> 4, z >> 4) { + continue; + } + if let Some(cost) = l.spawn_cost(e.entity, x, y, z) { + state.add_charge(e.block, cost.charge); + } + if e.is_mob { + state.add_local(x >> 4, z >> 4, e.category); + } + state.counts[e.category.index()] += 1; + } + state + } + fn add_charge(&mut self, pos: [i32; 3], charge: f64) { + if charge != 0.0 { + self.charges.push((pos, charge)); + } + } + /// `ChunkMap.getPlayersCloseForSpawning`: none past the natural spawn + /// chunk tracker's range of 8 chunks from every player, else the + /// non-spectators within 128 blocks of the chunk's centre. + fn players_near(&mut self, cx: i32, cz: i32) -> &[usize] { + let players = &self.players; + self.players_near.entry((cx, cz)).or_insert_with(|| { + let tracked = players.iter().any(|p| { + let (px, pz) = ( + (p.position[0].floor() as i32) >> 4, + (p.position[2].floor() as i32) >> 4, + ); + (px - cx).abs().max((pz - cz).abs()) <= 8 + }); + if !tracked { + return Vec::new(); + } + let (x, z) = (f64::from(cx * 16 + 8), f64::from(cz * 16 + 8)); + players + .iter() + .enumerate() + .filter(|(_, p)| { + let (dx, dz) = (x - p.position[0], z - p.position[2]); + !p.spectator && dx * dx + dz * dz < 16384.0 + }) + .map(|(i, _)| i) + .collect() + }) + } + fn add_local(&mut self, cx: i32, cz: i32, category: Category) { + let near = self.players_near(cx, cz).to_vec(); + for p in near { + self.player_counts.entry(p).or_insert([0; 8])[category.index()] += 1; + } + } + /// `canSpawnForCategoryGlobal`. + pub fn can_spawn_global(&self, category: Category) -> bool { + let max = category.max() * self.spawnable_chunks / 289; + self.counts[category.index()] < max + } + /// `canSpawnForCategoryLocal` (`LocalMobCapCalculator.canSpawn`). + pub fn can_spawn_local(&mut self, category: Category, cx: i32, cz: i32) -> bool { + let near = self.players_near(cx, cz).to_vec(); + near.into_iter().any(|p| { + self.player_counts + .get(&p) + .is_none_or(|c| c[category.index()] < category.max()) + }) + } + /// `getFilteredSpawningCategories`. + pub fn filtered_categories( + &self, + spawn_enemies: bool, + spawn_persistent: bool, + ) -> Vec { + Category::SPAWNING + .into_iter() + .filter(|&c| { + (spawn_enemies || c.friendly()) + && (spawn_persistent || !c.persistent()) + && self.can_spawn_global(c) + }) + .collect() + } + /// `SpawnState.canSpawn`: the spawn potential's energy change must stay + /// within the type's budget where it has a spawn cost. + fn can_spawn(&mut self, l: &L, entity: &str, pos: [i32; 3]) -> bool { + match l.spawn_cost(entity, pos[0], pos[1], pos[2]) { + None => { + self.last_checked = Some((pos, entity.to_owned(), 0.0)); + true + } + Some(cost) => { + self.last_checked = Some((pos, entity.to_owned(), cost.charge)); + self.energy_change(pos, cost.charge) <= cost.energy_budget + } + } + } + /// `PotentialCalculator.getPotentialEnergyChange`. + fn energy_change(&self, pos: [i32; 3], charge: f64) -> f64 { + if charge == 0.0 { + return 0.0; + } + let mut change = 0.0; + for (p, c) in &self.charges { + let d = [ + f64::from(p[0] - pos[0]), + f64::from(p[1] - pos[1]), + f64::from(p[2] - pos[2]), + ]; + let dist = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + change += if dist == 0.0 { + f64::INFINITY + } else { + c / dist.sqrt() + }; + } + change * charge + } + /// `SpawnState.afterSpawn`. + fn after_spawn( + &mut self, + l: &L, + entity: &str, + category: Category, + pos: [i32; 3], + ) { + let charge = match &self.last_checked { + Some((p, t, c)) if *p == pos && t == entity => *c, + _ => l + .spawn_cost(entity, pos[0], pos[1], pos[2]) + .map_or(0.0, |c| c.charge), + }; + self.add_charge(pos, charge); + self.counts[category.index()] += 1; + self.add_local(pos[0] >> 4, pos[2] >> 4, category); + } +} + +/// What a spawn pass did, in vanilla's order (for differential tests). +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// `getFilteredSpawningCategories`. + Categories(Vec), + /// `canSpawnForCategoryLocal` for the chunk. + Local(Category, bool), + /// `getRandomPosWithin`'s start. + Start(Category, [i32; 3]), + /// An attempt at a position (the nearest player lookup). + Try(i32, i32), + /// The type passed `isValidSpawnPostitionForType`; the spawn state's + /// potential test answered. + Test(String, [i32; 3], bool), + /// A mob spawned. + Spawn(String, [f64; 3], f32), +} +/// A mob the spawner is about to add: the level runs `finalizeSpawn` and +/// adds it, returning its finalized box and whether a tropical fish schools. +#[derive(Clone, Debug)] +pub struct SpawnRequest<'a> { + pub entity: &'a str, + pub species: Species, + pub position: [f64; 3], + pub yaw: f32, + /// Mobs of this group spawned before (the `SpawnGroupData`'s size). + pub group_index: u32, + pub reason: Reason, +} +#[derive(Clone, Copy, Debug)] +pub struct Spawned { + pub bounds: Aabb, + /// `TropicalFish.isSchool`. + pub school: bool, +} + +/// `NaturalSpawner.spawnForChunk` for the categories already filtered. +#[allow(clippy::too_many_arguments)] +pub fn spawn_for_chunk( + l: &L, + random: &mut R, + state: &mut SpawnState, + categories: &[Category], + chunk: (i32, i32), + spawn: &mut dyn FnMut(&L, &SpawnRequest) -> Option, + trace: &mut dyn FnMut(Event), +) { + for &category in categories { + let local = state.can_spawn_local(category, chunk.0, chunk.1); + trace(Event::Local(category, local)); + if local { + spawn_category_for_chunk(l, random, state, category, chunk, spawn, trace); + } + } +} +/// `NaturalSpawner.spawnCategoryForChunk`: `getRandomPosWithin` (a column of +/// the chunk, a height up to one above the world surface). +pub fn spawn_category_for_chunk( + l: &L, + random: &mut R, + state: &mut SpawnState, + category: Category, + chunk: (i32, i32), + spawn: &mut dyn FnMut(&L, &SpawnRequest) -> Option, + trace: &mut dyn FnMut(Event), +) { + let x = chunk.0 * 16 + random.next_int_bound(16).unwrap_or(0); + let z = chunk.1 * 16 + random.next_int_bound(16).unwrap_or(0); + let top = l.heightmap(Heightmap::WorldSurface, x, z) + 1; + let min = l.min_y(); + let y = min + random.next_int_bound(top - min + 1).unwrap_or(0); + trace(Event::Start(category, [x, y, z])); + if y >= min + 1 { + spawn_category_for_position(l, random, state, category, chunk, [x, y, z], spawn, trace); + } +} +/// `NaturalSpawner.spawnCategoryForPosition` with the spawn state's +/// `canSpawn` and `afterSpawn`. +#[allow(clippy::too_many_arguments)] +pub fn spawn_category_for_position( + l: &L, + random: &mut R, + state: &mut SpawnState, + category: Category, + chunk: (i32, i32), + start: [i32; 3], + spawn: &mut dyn FnMut(&L, &SpawnRequest) -> Option, + trace: &mut dyn FnMut(Event), +) { + let [x0, y, z0] = start; + if l.mob_data().state(l.state(x0, y, z0)).flags & super::data::REDSTONE_CONDUCTOR != 0 { + return; + } + let mut spawned: Vec = Vec::new(); + let mut cluster = 0u32; + for _ in 0..3 { + let (mut x, mut z) = (x0, z0); + let mut current: Option = None; + let mut group_index = 0u32; + let mut max = (random.next_float() * 4.0).ceil() as i32; + let mut ll = 0; + while ll < max { + ll += 1; + x += random.next_int_bound(6).unwrap_or(0) - random.next_int_bound(6).unwrap_or(0); + z += random.next_int_bound(6).unwrap_or(0) - random.next_int_bound(6).unwrap_or(0); + let (xx, zz) = (f64::from(x) + 0.5, f64::from(z) + 0.5); + trace(Event::Try(x, z)); + let Some(distance) = l.nearest_player_distance_sqr(xx, f64::from(y), zz) else { + continue; + }; + if !right_distance(l, chunk, [x, y, z], distance) { + continue; + } + if current.is_none() { + let reduced = l.biome_tag("minecraft:reduced_water_ambient_spawns", x, y, z); + let list = if category == Category::WaterAmbient + && reduced + && random.next_float() < 0.98 + { + None + } else { + weighted_pick(&mobs_at(l, category, x, y, z), random) + }; + let Some(entry) = list else { + break; + }; + max = sample_count(&entry, random) as i32; + current = Some(entry); + } + let entry = current.as_ref().unwrap_or_else(|| unreachable!()); + if !valid_position_for_type(l, random, category, entry, [x, y, z], distance) { + continue; + } + let passed = state.can_spawn(l, &entry.entity, [x, y, z]); + trace(Event::Test(entry.entity.clone(), [x, y, z], passed)); + if !passed { + continue; + } + // getMobForSpawn: a type the game cannot create ends the pass. + let Some((species, width, height, type_category)) = l.mob_type(&entry.entity) else { + return; + }; + let yaw = random.next_float() * 360.0; + let bounds = spawn_box(xx, f64::from(y), zz, width, height); + let despawn = f64::from(type_category.despawn_distance().pow(2)); + let far = distance > despawn && removed_when_far(species); + if far + || !mob_spawn_rules(species, l, x, y, z) + || !spawn_obstruction(species, l, bounds, &spawned, x, y, z) + { + continue; + } + let request = SpawnRequest { + entity: &entry.entity, + species, + position: [xx, f64::from(y), zz], + yaw, + group_index, + reason: Reason::Natural, + }; + let Some(result) = spawn(l, &request) else { + continue; + }; + group_index += 1; + spawned.push(result.bounds); + cluster += 1; + state.after_spawn(l, &entry.entity, type_category, [x, y, z]); + trace(Event::Spawn( + entry.entity.clone(), + [xx, f64::from(y), zz], + yaw, + )); + if cluster >= max_cluster_size(species) { + return; + } + // TropicalFish.isMaxGroupSizeReached. + if species == Species::TropicalFish && !result.school { + break; + } + } + } +} +/// `isRightDistanceToPlayerAndSpawnPoint`. +fn right_distance(l: &L, chunk: (i32, i32), pos: [i32; 3], distance: f64) -> bool { + if distance <= 576.0 { + return false; + } + if let Some(r) = l.respawn() { + let d = [ + f64::from(r[0]) + 0.5 - (f64::from(pos[0]) + 0.5), + f64::from(r[1]) + 0.5 - f64::from(pos[1]), + f64::from(r[2]) + 0.5 - (f64::from(pos[2]) + 0.5), + ]; + if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 24.0 * 24.0 { + return false; + } + } + let (cx, cz) = (pos[0] >> 4, pos[2] >> 4); + (cx, cz) == chunk || l.can_spawn_in_chunk(cx, cz) +} +/// `isValidSpawnPostitionForType`. +fn valid_position_for_type( + l: &L, + random: &mut R, + category: Category, + entry: &SpawnEntry, + pos: [i32; 3], + distance: f64, +) -> bool { + let Some((species, width, height, type_category)) = l.mob_type(&entry.entity) else { + return false; + }; + if type_category == Category::Misc { + return false; + } + let despawn = f64::from(type_category.despawn_distance().pow(2)); + if !spawns_far_from_player(species, type_category) && distance > despawn { + return false; + } + let [x, y, z] = pos; + if !mobs_at(l, category, x, y, z) + .iter() + .any(|e| same_spawner(e, entry)) + { + return false; + } + if !spawn_rules::is_spawn_position_ok(species, l, x, y, z) { + return false; + } + if !spawn_rules::check_spawn_rules(species, l, Reason::Natural, random, x, y, z) { + return false; + } + l.no_collision(spawn_box( + f64::from(x) + 0.5, + f64::from(y), + f64::from(z) + 0.5, + width, + height, + )) +} + +/// What chunk generation spawning did (for differential tests). +#[derive(Clone, Debug, PartialEq)] +pub enum GenEvent { + /// A pack: its type and count. + Pack(String, u32), + /// An attempt at the top non-colliding position of a column. + Try([i32; 3]), + Spawn(String, [f64; 3], f32), +} +/// `NaturalSpawner.spawnMobsForChunkGeneration`: creature packs placed on +/// the chunk's surface. `rules` is the level's own random, which the spawn +/// predicates draw from. +#[allow(clippy::too_many_arguments)] +pub fn spawn_mobs_for_chunk_generation( + l: &L, + source: [i32; 3], + chunk: (i32, i32), + random: &mut R, + rules: &mut Q, + spawn: &mut dyn FnMut(&L, &SpawnRequest) -> Option, + trace: &mut dyn FnMut(GenEvent), +) { + if !l.spawn_mobs() { + return; + } + let [sx, sy, sz] = source; + let mobs = l + .biome_spawns(sx, sy, sz) + .and_then(|b| b.get("creature")) + .cloned() + .unwrap_or_default(); + if mobs.iter().map(|e| e.weight).sum::() == 0 { + return; + } + let probability = l.creature_probability(sx, sy, sz); + let (xo, zo) = (chunk.0 * 16, chunk.1 * 16); + while random.next_float() < probability { + let Some(entry) = weighted_pick(&mobs, random) else { + continue; + }; + let count = sample_count(&entry, random); + trace(GenEvent::Pack(entry.entity.clone(), count)); + let mut group_index = 0u32; + let mut spawned: Vec = Vec::new(); + let mut x = xo + random.next_int_bound(16).unwrap_or(0); + let mut z = zo + random.next_int_bound(16).unwrap_or(0); + let (start_x, start_z) = (x, z); + let kind = l.mob_type(&entry.entity); + for _ in 0..count { + let mut success = false; + let mut attempts = 0; + while !success && attempts < 4 { + attempts += 1; + let Some((species, width, height, _)) = kind else { + break; + }; + let pos = top_non_colliding(l, &entry.entity, x, z); + trace(GenEvent::Try(pos)); + if spawn_rules::is_spawn_position_ok(species, l, pos[0], pos[1], pos[2]) { + let fx = f64::from(x).clamp( + f64::from(xo) + f64::from(width), + f64::from(xo) + 16.0 - f64::from(width), + ); + let fz = f64::from(z).clamp( + f64::from(zo) + f64::from(width), + f64::from(zo) + 16.0 - f64::from(width), + ); + let fy = f64::from(pos[1]); + let (bx, bz) = (fx.floor() as i32, fz.floor() as i32); + if !l.no_collision(spawn_box(fx, fy, fz, width, height)) + || !spawn_rules::check_spawn_rules( + species, + l, + Reason::ChunkGeneration, + rules, + bx, + pos[1], + bz, + ) + { + continue; + } + let yaw = random.next_float() * 360.0; + let bounds = spawn_box(fx, fy, fz, width, height); + if mob_spawn_rules(species, l, bx, pos[1], bz) + && spawn_obstruction(species, l, bounds, &spawned, bx, pos[1], bz) + { + let request = SpawnRequest { + entity: &entry.entity, + species, + position: [fx, fy, fz], + yaw, + group_index, + reason: Reason::ChunkGeneration, + }; + if let Some(result) = spawn(l, &request) { + group_index += 1; + spawned.push(result.bounds); + trace(GenEvent::Spawn(entry.entity.clone(), [fx, fy, fz], yaw)); + success = true; + } + } + } + x += random.next_int_bound(5).unwrap_or(0) - random.next_int_bound(5).unwrap_or(0); + z += random.next_int_bound(5).unwrap_or(0) - random.next_int_bound(5).unwrap_or(0); + while x < xo || x >= xo + 16 || z < zo || z >= zo + 16 { + x = start_x + random.next_int_bound(5).unwrap_or(0) + - random.next_int_bound(5).unwrap_or(0); + z = start_z + random.next_int_bound(5).unwrap_or(0) + - random.next_int_bound(5).unwrap_or(0); + } + } + } + } +} +/// `getTopNonCollidingPos`: the type's heightmap, under the ceiling in +/// dimensions that have one, then the placement type's adjustment. +fn top_non_colliding(l: &L, entity: &str, x: i32, z: i32) -> [i32; 3] { + let heightmap = Heightmap::from_name(l.mob_data().heightmap(entity)); + let mut y = l.heightmap(heightmap, x, z); + if l.has_ceiling() { + loop { + y -= 1; + if l.facts().is_air(l.state(x, y, z)) { + break; + } + } + loop { + y -= 1; + if !(l.facts().is_air(l.state(x, y, z)) && y > l.min_y()) { + break; + } + } + } + if l.mob_data().placement(entity) == super::data::Placement::OnGround + && l.pathfindable_land(x, y - 1, z) + { + y -= 1; + } + [x, y, z] +}