Merge branch 'parity-base' into parity/saves
# Conflicts: # README.md
This commit is contained in:
@@ -0,0 +1,688 @@
|
||||
//! Natural spawning decisions for differential tests against vanilla
|
||||
//! (tools/test_natural_spawn_parity.py): reads the box-world cases of
|
||||
//! `VanillaNaturalSpawnOracle` and prints what `mobs::spawn_selection` does in
|
||||
//! the same order and format.
|
||||
//!
|
||||
//! The oracle runs `finalizeSpawn` with a fixed random (nextInt 0, nextFloat
|
||||
//! 0.75); `neutral_box` is the box that leaves a mob with: polar bears,
|
||||
//! ocelots and rabbits after the first of their group are babies (chance
|
||||
//! 1.0), foxes and axolotls from the third, sulfur cubes have size 2, salmon
|
||||
//! are small, slimes and magma cubes keep size 1, tropical fish school.
|
||||
//!
|
||||
//! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
biome::{Biomes, SpawnEntry},
|
||||
blocks::BlockFacts,
|
||||
collisions::{self, LookupCollisions, no_collision_empty},
|
||||
items::Items,
|
||||
mobs::{
|
||||
MobTypes, Species,
|
||||
data::MobData,
|
||||
spawn_rules::{Dimension, SpawnLevel},
|
||||
spawn_selection::{
|
||||
self, Category, Counted, Event, GenEvent, Heightmap, NaturalLevel, SpawnCost,
|
||||
SpawnPlayer, SpawnRequest, SpawnState, Spawned, StructureAt, StructureSpawns,
|
||||
spawn_box,
|
||||
},
|
||||
species::{self, Baby},
|
||||
},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Aabb,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::BlockCollisionRegistry, chunk::BlockState, registry::BlockStateId,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
fmt::Write as _,
|
||||
fs,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Bx([i32; 6]);
|
||||
impl Bx {
|
||||
fn parse(s: &str) -> Self {
|
||||
let v: Vec<i32> = s.split(',').map(|n| n.parse().unwrap_or(0)).collect();
|
||||
Self([v[0], v[1], v[2], v[3], v[4], v[5]])
|
||||
}
|
||||
fn has(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
let b = self.0;
|
||||
x >= b[0] && x <= b[3] && y >= b[1] && y <= b[4] && z >= b[2] && z <= b[5]
|
||||
}
|
||||
}
|
||||
struct Start {
|
||||
id: String,
|
||||
pieces: Vec<Bx>,
|
||||
/// The start's bounding box (pieces encapsulated, inflated by 12 for
|
||||
/// terrain adaptation).
|
||||
bounds: Bx,
|
||||
}
|
||||
|
||||
struct Shared<'a> {
|
||||
facts: &'a BlockFacts,
|
||||
data: &'a MobData,
|
||||
block_tags: &'a HashMap<String, HashSet<String>>,
|
||||
types: &'a MobTypes,
|
||||
biomes: &'a Biomes,
|
||||
structures: &'a StructureSpawns,
|
||||
collision: &'a BlockCollisionRegistry<'a>,
|
||||
air: BlockStateId,
|
||||
}
|
||||
struct World<'a> {
|
||||
s: &'a Shared<'a>,
|
||||
blocks: Vec<(Bx, BlockStateId)>,
|
||||
lights: Vec<(Bx, i32, i32)>,
|
||||
biomes: Vec<(Bx, String)>,
|
||||
biome: String,
|
||||
sky: i32,
|
||||
light: i32,
|
||||
darken: i32,
|
||||
thunder: bool,
|
||||
sea: i32,
|
||||
seed: i64,
|
||||
peaceful: bool,
|
||||
dimension: Dimension,
|
||||
dimension_id: String,
|
||||
slime: f32,
|
||||
starts: Vec<Start>,
|
||||
players: Vec<([f64; 3], String)>,
|
||||
respawn: Option<[i32; 3]>,
|
||||
unloaded: HashSet<(i32, i32)>,
|
||||
spawn_mobs: bool,
|
||||
/// Boxes of living entities (case entities, then spawned mobs).
|
||||
entities: RefCell<Vec<Aabb>>,
|
||||
}
|
||||
impl World<'_> {
|
||||
fn biome_at(&self, x: i32, y: i32, z: i32) -> &str {
|
||||
self.biomes
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(b, _)| b.has(x, y, z))
|
||||
.map_or(&self.biome, |(_, n)| n)
|
||||
}
|
||||
fn biome_info(&self, x: i32, y: i32, z: i32) -> Option<&horizon_client::biome::BiomeInfo> {
|
||||
let i = *self.s.biomes.index.get(self.biome_at(x, y, z))?;
|
||||
Some(self.s.biomes.get(i))
|
||||
}
|
||||
fn lights_at(&self, x: i32, y: i32, z: i32) -> (i32, i32) {
|
||||
self.lights
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(b, ..)| b.has(x, y, z))
|
||||
.map_or((self.sky, self.light), |(_, s, b)| (*s, *b))
|
||||
}
|
||||
}
|
||||
impl SpawnLevel for World<'_> {
|
||||
fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId {
|
||||
self.blocks
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(b, _)| b.has(x, y, z))
|
||||
.map_or(self.s.air, |(_, s)| *s)
|
||||
}
|
||||
fn facts(&self) -> &BlockFacts {
|
||||
self.s.facts
|
||||
}
|
||||
fn mob_data(&self) -> &MobData {
|
||||
self.s.data
|
||||
}
|
||||
fn block_tag(&self, tag: &str, block: &str) -> bool {
|
||||
self.s
|
||||
.block_tags
|
||||
.get(tag)
|
||||
.is_some_and(|s| s.contains(block))
|
||||
}
|
||||
fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool {
|
||||
self.s
|
||||
.data
|
||||
.biome_tags
|
||||
.get(tag)
|
||||
.is_some_and(|s| s.contains(self.biome_at(x, y, z)))
|
||||
}
|
||||
fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 {
|
||||
self.lights_at(x, y, z).0
|
||||
}
|
||||
fn block_light(&self, x: i32, y: i32, z: i32) -> i32 {
|
||||
self.lights_at(x, y, z).1
|
||||
}
|
||||
fn sky_darken(&self) -> i32 {
|
||||
self.darken
|
||||
}
|
||||
fn thundering(&self) -> bool {
|
||||
self.thunder
|
||||
}
|
||||
fn sea_level(&self) -> i32 {
|
||||
self.sea
|
||||
}
|
||||
fn world_surface(&self, x: i32, z: i32) -> i32 {
|
||||
self.heightmap(Heightmap::WorldSurface, x, z)
|
||||
}
|
||||
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.players.iter().any(|(p, mode)| {
|
||||
let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2);
|
||||
(mode == "survival" || mode == "adventure") && d < distance * distance
|
||||
})
|
||||
}
|
||||
}
|
||||
impl NaturalLevel for World<'_> {
|
||||
fn min_y(&self) -> i32 {
|
||||
if self.dimension == Dimension::Overworld {
|
||||
-64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
fn max_y(&self) -> i32 {
|
||||
if self.dimension == Dimension::Overworld {
|
||||
319
|
||||
} else {
|
||||
255
|
||||
}
|
||||
}
|
||||
fn ambient_light(&self) -> f32 {
|
||||
match self.dimension {
|
||||
Dimension::Overworld => 0.0,
|
||||
Dimension::Nether => 0.1,
|
||||
Dimension::End => 0.25,
|
||||
}
|
||||
}
|
||||
fn has_ceiling(&self) -> bool {
|
||||
self.dimension == Dimension::Nether
|
||||
}
|
||||
fn mob_type(&self, entity: &str) -> Option<(Species, f32, f32, Category)> {
|
||||
let t = self.s.types.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<String, Vec<SpawnEntry>>> {
|
||||
self.biome_info(x, y, z).map(|b| &b.spawns)
|
||||
}
|
||||
fn spawn_cost(&self, entity: &str, x: i32, y: i32, z: i32) -> Option<SpawnCost> {
|
||||
self.biome_info(x, y, z)?.spawn_costs.get(entity).copied()
|
||||
}
|
||||
fn creature_probability(&self, x: i32, y: i32, z: i32) -> f32 {
|
||||
self.biome_info(x, y, z)
|
||||
.map_or(0.1, |b| b.creature_probability)
|
||||
}
|
||||
fn structures_at(&self, x: i32, y: i32, z: i32) -> Vec<StructureAt> {
|
||||
let (cx, cz) = (x >> 4, z >> 4);
|
||||
let mut out: Vec<StructureAt> = Vec::new();
|
||||
for start in &self.starts {
|
||||
let b = start.bounds.0;
|
||||
// Referenced: the start's box reaches the chunk's columns.
|
||||
if b[3] < cx * 16 || b[0] > cx * 16 + 15 || b[5] < cz * 16 || b[2] > cz * 16 + 15 {
|
||||
continue;
|
||||
}
|
||||
let in_piece = start.pieces.iter().any(|p| p.has(x, y, z));
|
||||
let in_bounds = start.bounds.has(x, y, z);
|
||||
match out.iter_mut().find(|s| s.id == start.id) {
|
||||
Some(s) => {
|
||||
s.in_piece |= in_piece;
|
||||
s.in_bounds |= in_bounds;
|
||||
}
|
||||
None => out.push(StructureAt {
|
||||
id: start.id.clone(),
|
||||
in_piece,
|
||||
in_bounds,
|
||||
}),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn structure_spawns(&self) -> &StructureSpawns {
|
||||
self.s.structures
|
||||
}
|
||||
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
|
||||
let mut best: Option<f64> = None;
|
||||
for (p, mode) in &self.players {
|
||||
if mode == "spectator" {
|
||||
continue;
|
||||
}
|
||||
let d = [p[0] - x, p[1] - y, p[2] - z];
|
||||
let d = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
||||
if best.is_none_or(|b| d < b) {
|
||||
best = Some(d);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
fn respawn(&self) -> Option<[i32; 3]> {
|
||||
self.respawn
|
||||
}
|
||||
fn can_spawn_in_chunk(&self, cx: i32, cz: i32) -> bool {
|
||||
!self.unloaded.contains(&(cx, cz))
|
||||
}
|
||||
fn no_collision(&self, bounds: Aabb) -> bool {
|
||||
let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z);
|
||||
let mut world = LookupCollisions {
|
||||
block: &lookup,
|
||||
binding: self.s.collision,
|
||||
};
|
||||
no_collision_empty(&mut world, bounds)
|
||||
}
|
||||
fn unobstructed(&self, bounds: Aabb) -> bool {
|
||||
!self.entities.borrow().iter().any(|b| b.intersects(bounds))
|
||||
}
|
||||
fn spawn_mobs(&self) -> bool {
|
||||
self.spawn_mobs
|
||||
}
|
||||
fn heightmap(&self, kind: Heightmap, x: i32, z: i32) -> i32 {
|
||||
(self.min_y()..=self.max_y())
|
||||
.rev()
|
||||
.find(|&y| spawn_selection::heightmap_blocks(self, kind, x, y, z))
|
||||
.map_or(self.min_y(), |y| y + 1)
|
||||
}
|
||||
fn pathfindable_land(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
self.s.data.state(self.state(x, y, z)).flags & horizon_client::mobs::data::LAND != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random.
|
||||
fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb {
|
||||
let t = &l.s.types.types[r.entity];
|
||||
let (mut w, mut h) = (t.width as f32, t.height as f32);
|
||||
let baby = match r.species {
|
||||
Species::PolarBear | Species::Ocelot | Species::Rabbit => r.group_index > 0,
|
||||
Species::Fox | Species::Axolotl => r.group_index >= 2,
|
||||
_ => false,
|
||||
};
|
||||
if baby {
|
||||
match species::def(r.species).baby {
|
||||
Baby::Abs(bw, bh, _) => (w, h) = (bw as f32, bh as f32),
|
||||
Baby::Scale(s, _) => (w, h) = (w * s as f32, h * s as f32),
|
||||
Baby::None => {}
|
||||
}
|
||||
}
|
||||
match r.species {
|
||||
Species::SulfurCube => (w, h) = (w * 2.0, h * 2.0),
|
||||
Species::Salmon => (w, h) = (w * 0.5, h * 0.5),
|
||||
_ => {}
|
||||
}
|
||||
let [x, y, z] = r.position;
|
||||
spawn_box(x, y, z, w, h)
|
||||
}
|
||||
|
||||
fn parse_state(spec: &str) -> BlockState {
|
||||
let (name, props) = match spec.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (spec, ""),
|
||||
};
|
||||
BlockState {
|
||||
name: name.to_owned(),
|
||||
properties: props
|
||||
.split(',')
|
||||
.filter(|p| !p.is_empty())
|
||||
.filter_map(|p| p.split_once('='))
|
||||
.map(|(k, v)| (k.to_owned(), v.to_owned()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
fn bits(v: f64) -> String {
|
||||
format!("{:x}", v.to_bits())
|
||||
}
|
||||
/// The yaw as the oracle prints it: a cube mob grown by `finalizeSpawn`
|
||||
/// (sulfur cubes, size 2 under the fixed random) takes its constructor's
|
||||
/// head rotation from the entity's unseeded random.
|
||||
fn yaw_text(entity: &str, v: f32) -> String {
|
||||
if entity == "minecraft:sulfur_cube" {
|
||||
"head".to_owned()
|
||||
} else {
|
||||
format!("{:x}", v.to_bits())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let root = Path::new(
|
||||
args.get(1)
|
||||
.ok_or("usage: natural_spawn_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 biomes = Biomes::load(root)?;
|
||||
let structures = StructureSpawns::load(root);
|
||||
let collision = collisions::load(root, registry)?;
|
||||
let shared = Shared {
|
||||
facts: &facts,
|
||||
data: &data,
|
||||
block_tags: &items.block_tags,
|
||||
types: &types,
|
||||
biomes: &biomes,
|
||||
structures: &structures,
|
||||
collision: &collision,
|
||||
air: facts.air,
|
||||
};
|
||||
let mut adaptation: HashMap<String, bool> = HashMap::new();
|
||||
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 indexed = |prefix: &str| -> Vec<&str> {
|
||||
(0..)
|
||||
.map_while(|i| c.get(format!("{prefix}{i}").as_str()).copied())
|
||||
.collect()
|
||||
};
|
||||
let mut blocks = Vec::new();
|
||||
for k in indexed("k") {
|
||||
let (b, s) = k.split_once('/').ok_or("bad block box")?;
|
||||
blocks.push((Bx::parse(b), registry.resolve(&parse_state(s))?));
|
||||
}
|
||||
let lights = indexed("l")
|
||||
.into_iter()
|
||||
.filter_map(|l| {
|
||||
let (b, v) = l.split_once('/')?;
|
||||
let (s, k) = v.split_once(',')?;
|
||||
Some((Bx::parse(b), s.parse().ok()?, k.parse().ok()?))
|
||||
})
|
||||
.collect();
|
||||
let biome_boxes = indexed("b")
|
||||
.into_iter()
|
||||
.filter_map(|l| {
|
||||
let (b, n) = l.split_once('/')?;
|
||||
Some((Bx::parse(b), n.to_owned()))
|
||||
})
|
||||
.collect();
|
||||
let mut starts = Vec::new();
|
||||
for s in indexed("s") {
|
||||
let (id, pieces) = s.split_once('/').ok_or("bad structure")?;
|
||||
let pieces: Vec<Bx> = pieces.split(';').map(Bx::parse).collect();
|
||||
let mut b = pieces[0].0;
|
||||
for p in &pieces[1..] {
|
||||
for i in 0..3 {
|
||||
b[i] = b[i].min(p.0[i]);
|
||||
b[i + 3] = b[i + 3].max(p.0[i + 3]);
|
||||
}
|
||||
}
|
||||
let adapts = *adaptation.entry(id.to_owned()).or_insert_with(|| {
|
||||
let path = root.join(format!(
|
||||
"data/minecraft/worldgen/structure/{}.json",
|
||||
id.trim_start_matches("minecraft:")
|
||||
));
|
||||
fs::read(path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
|
||||
.and_then(|v| v["terrain_adaptation"].as_str().map(|a| a != "none"))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
if adapts {
|
||||
for i in 0..3 {
|
||||
b[i] -= 12;
|
||||
b[i + 3] += 12;
|
||||
}
|
||||
}
|
||||
starts.push(Start {
|
||||
id: id.to_owned(),
|
||||
pieces,
|
||||
bounds: Bx(b),
|
||||
});
|
||||
}
|
||||
let players = indexed("p")
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
let mut parts = p.split('/');
|
||||
let v: Vec<f64> = parts
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap_or(0.0))
|
||||
.collect();
|
||||
(
|
||||
[v[0], v[1], v[2]],
|
||||
parts.next().unwrap_or("survival").to_owned(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let dimension_id = get("dim", "minecraft:overworld");
|
||||
let dimension = match dimension_id.as_str() {
|
||||
"minecraft:the_nether" => Dimension::Nether,
|
||||
"minecraft:the_end" => Dimension::End,
|
||||
_ => Dimension::Overworld,
|
||||
};
|
||||
let respawn = {
|
||||
let r = get("respawn", "0,-1000,0/minecraft:overworld");
|
||||
let (p, d) = r.split_once('/').ok_or("bad respawn")?;
|
||||
let v: Vec<i32> = p.split(',').map(|n| n.parse().unwrap_or(0)).collect();
|
||||
(d == dimension_id).then_some([v[0], v[1], v[2]])
|
||||
};
|
||||
let unloaded = c
|
||||
.get("unloaded")
|
||||
.map(|u| {
|
||||
u.split(';')
|
||||
.filter_map(|p| {
|
||||
let (x, z) = p.split_once(',')?;
|
||||
Some((x.parse().ok()?, z.parse().ok()?))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
// Case entities: (type, position, persistent).
|
||||
let mut case_entities = Vec::new();
|
||||
for e in indexed("e") {
|
||||
let parts: Vec<&str> = e.split('/').collect();
|
||||
let v: Vec<f64> = parts[1]
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap_or(0.0))
|
||||
.collect();
|
||||
// EntityType.create makes no monsters in peaceful.
|
||||
if get("difficulty", "normal") == "peaceful"
|
||||
&& types.types.get(parts[0]).is_some_and(|t| {
|
||||
!horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species)
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
case_entities.push((
|
||||
parts[0].to_owned(),
|
||||
[v[0], v[1], v[2]],
|
||||
parts.get(2) == Some(&"p"),
|
||||
));
|
||||
}
|
||||
let world = World {
|
||||
s: &shared,
|
||||
blocks,
|
||||
lights,
|
||||
biomes: biome_boxes,
|
||||
biome: get("biome", "minecraft:plains"),
|
||||
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()?,
|
||||
seed: get("wseed", "0").parse()?,
|
||||
peaceful: get("difficulty", "normal") == "peaceful",
|
||||
dimension,
|
||||
dimension_id: dimension_id.clone(),
|
||||
slime: get("slime", "0.0").parse()?,
|
||||
starts,
|
||||
players,
|
||||
respawn,
|
||||
unloaded,
|
||||
spawn_mobs: get("rules", "1") != "0",
|
||||
entities: RefCell::new(
|
||||
case_entities
|
||||
.iter()
|
||||
.filter_map(|(t, p, _)| {
|
||||
let t = types.types.get(t)?;
|
||||
Some(spawn_box(p[0], p[1], p[2], t.width as f32, t.height as f32))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
let _ = &world.dimension_id;
|
||||
let chunk = {
|
||||
let v: Vec<i32> = get("chunk", "0,0")
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap_or(0))
|
||||
.collect();
|
||||
(v[0], v[1])
|
||||
};
|
||||
let mut random = LegacyRandom::new(get("seed", "0").parse()?);
|
||||
let mut log: Vec<String> = Vec::new();
|
||||
let mut spawn = |l: &World, r: &SpawnRequest| -> Option<Spawned> {
|
||||
let bounds = neutral_box(l, r);
|
||||
l.entities.borrow_mut().push(bounds);
|
||||
Some(Spawned {
|
||||
bounds,
|
||||
school: true,
|
||||
})
|
||||
};
|
||||
let mode = get("mode", "chunk");
|
||||
if mode == "gen" {
|
||||
let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?);
|
||||
// The level random of the spawn predicates: no creature's predicate
|
||||
// draws from it (the oracle's answers fixed values).
|
||||
let mut rules = LegacyRandom::new(0);
|
||||
let mut spawns = Vec::new();
|
||||
let source = [chunk.0 * 16, world.max_y(), chunk.1 * 16];
|
||||
spawn_selection::spawn_mobs_for_chunk_generation(
|
||||
&world,
|
||||
source,
|
||||
chunk,
|
||||
&mut gen_random,
|
||||
&mut rules,
|
||||
&mut spawn,
|
||||
&mut |e| match e {
|
||||
GenEvent::Column(x, z) => log.push(format!("col {x} {z}")),
|
||||
GenEvent::Spawn(t, p, yaw) => spawns.push(format!(
|
||||
"spawn {t} {} {} {} {}",
|
||||
bits(p[0]),
|
||||
bits(p[1]),
|
||||
bits(p[2]),
|
||||
yaw_text(&t, yaw)
|
||||
)),
|
||||
},
|
||||
);
|
||||
log.extend(spawns);
|
||||
log.push(format!(
|
||||
"next {}",
|
||||
gen_random.next_int_bound(1000).unwrap_or(0)
|
||||
));
|
||||
} else {
|
||||
let counted: Vec<Counted> = case_entities
|
||||
.iter()
|
||||
.filter_map(|(t, p, persistent)| {
|
||||
let kind = types.types.get(t)?;
|
||||
Some(Counted {
|
||||
entity: t,
|
||||
category: Category::from_name(&kind.category),
|
||||
block: [
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
],
|
||||
is_mob: true,
|
||||
persistent: *persistent,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let players = world
|
||||
.players
|
||||
.iter()
|
||||
.map(|(p, mode)| SpawnPlayer {
|
||||
position: *p,
|
||||
spectator: mode == "spectator",
|
||||
})
|
||||
.collect();
|
||||
let mut state = SpawnState::new(
|
||||
&world,
|
||||
get("chunkcount", "289").parse()?,
|
||||
players,
|
||||
&counted,
|
||||
|cx, cz| !world.unloaded.contains(&(cx, cz)),
|
||||
);
|
||||
let mut trace = |e: Event| {
|
||||
log.push(match e {
|
||||
Event::Categories(list) => format!(
|
||||
"cats {}",
|
||||
list.iter().map(|c| c.name()).collect::<Vec<_>>().join(",")
|
||||
),
|
||||
Event::Local(c, ok) => format!("local {} {ok}", c.name()),
|
||||
Event::Start(c, p) => format!("start {} {} {} {}", c.name(), p[0], p[1], p[2]),
|
||||
Event::Try(x, z) => format!("try {x} {z}"),
|
||||
Event::Test(t, p, ok) => format!("test {t} {} {} {} {ok}", p[0], p[1], p[2]),
|
||||
Event::Spawn(t, p, yaw) => format!(
|
||||
"spawn {t} {} {} {} {}",
|
||||
bits(p[0]),
|
||||
bits(p[1]),
|
||||
bits(p[2]),
|
||||
yaw_text(&t, yaw)
|
||||
),
|
||||
})
|
||||
};
|
||||
if mode == "pos" {
|
||||
let category = Category::from_name(&get("cat", "monster"));
|
||||
let v: Vec<i32> = get("start", "0,0,0")
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap_or(0))
|
||||
.collect();
|
||||
spawn_selection::spawn_category_for_position(
|
||||
&world,
|
||||
&mut random,
|
||||
&mut state,
|
||||
category,
|
||||
chunk,
|
||||
[v[0], v[1], v[2]],
|
||||
&mut spawn,
|
||||
&mut trace,
|
||||
);
|
||||
} else {
|
||||
let categories = state
|
||||
.filtered_categories(get("enemies", "1") == "1", get("persistent", "1") == "1");
|
||||
trace(Event::Categories(categories.clone()));
|
||||
spawn_selection::spawn_for_chunk(
|
||||
&world,
|
||||
&mut random,
|
||||
&mut state,
|
||||
&categories,
|
||||
chunk,
|
||||
&mut spawn,
|
||||
&mut trace,
|
||||
);
|
||||
}
|
||||
log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0)));
|
||||
}
|
||||
let _ = writeln!(out, "{name} {}", log.join(" ; "));
|
||||
}
|
||||
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -17,11 +17,16 @@ pub struct SpawnEntry {
|
||||
pub weight: u32,
|
||||
pub min: u32,
|
||||
pub max: u32,
|
||||
/// A `ConstantInt` count (sampling draws nothing).
|
||||
pub constant: bool,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BiomeInfo {
|
||||
/// `natural_mob_spawns` by category (creature, monster, ...).
|
||||
pub spawns: HashMap<String, Vec<SpawnEntry>>,
|
||||
/// `natural_mob_spawns` spawn costs by entity type.
|
||||
pub spawn_costs: HashMap<String, crate::mobs::spawn_selection::SpawnCost>,
|
||||
/// The `gameplay/creature_world_gen_spawn_probability` attribute.
|
||||
pub creature_probability: f32,
|
||||
pub name: String,
|
||||
pub temperature: f32,
|
||||
@@ -103,37 +108,26 @@ impl Biomes {
|
||||
_ => GrassModifier::None,
|
||||
};
|
||||
let mut spawns: HashMap<String, Vec<SpawnEntry>> = 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 = entries
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let (min, max) = match &e["count"] {
|
||||
Value::Number(n) => {
|
||||
let n = n.as_u64().unwrap_or(1) as u32;
|
||||
(n, n)
|
||||
}
|
||||
c => (
|
||||
c["min_inclusive"].as_u64().unwrap_or(1) as u32,
|
||||
c["max_inclusive"].as_u64().unwrap_or(1) as u32,
|
||||
),
|
||||
};
|
||||
Some(SpawnEntry {
|
||||
entity: e["type"].as_str()?.to_owned(),
|
||||
weight: e["weight"].as_u64().unwrap_or(1) as u32,
|
||||
min,
|
||||
max,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
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),
|
||||
|
||||
@@ -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<W, E>(world: &mut W, bounds: Aabb) -> bool
|
||||
where
|
||||
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
|
||||
{
|
||||
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;
|
||||
@@ -166,3 +183,91 @@ impl PowderSnowWorld for SceneCollisions<'_, '_> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collision queries over any block lookup (test worlds without chunks):
|
||||
/// every chunk is present, nothing is suffocating, no entities collide.
|
||||
pub struct LookupCollisions<'w, 'r> {
|
||||
pub block: &'w dyn Fn(i32, i32, i32) -> horizon_world::registry::BlockStateId,
|
||||
pub binding: &'w BlockCollisionRegistry<'r>,
|
||||
}
|
||||
impl BlockCollisionWorld for LookupCollisions<'_, '_> {
|
||||
type Error = io::Error;
|
||||
type Chunk = ChunkPos;
|
||||
fn collision_chunk(&mut self, p: ChunkPos) -> io::Result<Option<ChunkPos>> {
|
||||
Ok(Some(p))
|
||||
}
|
||||
fn collision_block(&mut self, _: ChunkPos, p: BlockPos) -> io::Result<CollisionBlock> {
|
||||
self.binding.collision_block((self.block)(p.x, p.y, p.z))
|
||||
}
|
||||
fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
fn context_shape(
|
||||
&mut self,
|
||||
block: CollisionBlock,
|
||||
p: BlockPos,
|
||||
context: &CollisionContext<'_>,
|
||||
) -> io::Result<VoxelShape> {
|
||||
self.binding
|
||||
.collision_shape_with_context(self, block.state, p, context)
|
||||
.map_err(io::Error::other)
|
||||
}
|
||||
}
|
||||
impl EntityMovementWorld for LookupCollisions<'_, '_> {
|
||||
type Error = io::Error;
|
||||
fn entity_collisions(&mut self, _: EntityIdentity, _: Aabb) -> io::Result<Vec<VoxelShape>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn movement_border(&mut self, _: EntityIdentity, _: Aabb) -> io::Result<Option<VoxelShape>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
impl DynamicSupportWorld for LookupCollisions<'_, '_> {
|
||||
type Error = io::Error;
|
||||
fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result<Option<bool>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result<Option<VoxelShape>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
impl DynamicCollisionWorld for LookupCollisions<'_, '_> {
|
||||
fn shulker_collision_state(
|
||||
&mut self,
|
||||
_: [i32; 3],
|
||||
) -> io::Result<Option<ShulkerCollisionState>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
impl LiquidCollisionWorld for LookupCollisions<'_, '_> {
|
||||
type Error = io::Error;
|
||||
fn entity_liquid_shape(&mut self, _: EntityIdentity) -> io::Result<VoxelShape> {
|
||||
Ok(VoxelShape::empty())
|
||||
}
|
||||
fn fluid(&mut self, p: BlockPos) -> io::Result<FluidState> {
|
||||
FluidState::from_block(
|
||||
self.binding
|
||||
.registry()
|
||||
.state((self.block)(p.x, p.y, p.z))
|
||||
.ok_or_else(|| io::Error::other("fluid state outside registry"))?,
|
||||
)
|
||||
}
|
||||
fn entity_can_stand(&mut self, _: EntityIdentity, _: FluidState) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
impl PowderSnowWorld for LookupCollisions<'_, '_> {
|
||||
type Error = io::Error;
|
||||
fn powder_snow_entity(&mut self, _: EntityIdentity) -> io::Result<PowderSnowEntity> {
|
||||
Ok(PowderSnowEntity {
|
||||
fall_distance: 0.0,
|
||||
falling_block: false,
|
||||
})
|
||||
}
|
||||
fn powder_snow_walkable_tag(&mut self, _: EntityIdentity) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
fn feet_are_leather_boots(&mut self, _: EntityIdentity) -> io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ mod mount_menu;
|
||||
mod mounts;
|
||||
mod music;
|
||||
mod names;
|
||||
mod natural_spawning;
|
||||
mod nautili;
|
||||
mod options;
|
||||
mod packs;
|
||||
@@ -755,9 +756,6 @@ struct Game<'a> {
|
||||
adv_ui: advancements_screen::AdvUi,
|
||||
camera_type: perspective::CameraType,
|
||||
fangs: fangs::FangState,
|
||||
/// Structure `spawn_overrides`: structure -> category -> (piece only, spawns).
|
||||
spawn_overrides:
|
||||
HashMap<String, HashMap<String, (bool, Vec<horizon_client::biome::SpawnEntry>)>>,
|
||||
/// The local player as a model (third person, the inventory).
|
||||
player_model: Option<Mob>,
|
||||
}
|
||||
@@ -8133,7 +8131,6 @@ pub fn run() -> Result<()> {
|
||||
adv_ui: Default::default(),
|
||||
camera_type: Default::default(),
|
||||
fangs: Default::default(),
|
||||
spawn_overrides: HashMap::new(),
|
||||
player_model: None,
|
||||
};
|
||||
game.ui.vanilla_root = vanilla_root;
|
||||
|
||||
@@ -37,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)>,
|
||||
@@ -355,99 +344,6 @@ impl Game<'_> {
|
||||
}
|
||||
horizon_client::chunk::MIN_Y
|
||||
}
|
||||
fn weighted_entry(
|
||||
&mut self,
|
||||
entries: &[horizon_client::biome::SpawnEntry],
|
||||
) -> Option<horizon_client::biome::SpawnEntry> {
|
||||
let total: u32 = entries.iter().map(|e| e.weight).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut r = self.world.random.next_int_bound(total as i32).ok()? as u32;
|
||||
for e in entries {
|
||||
if r < e.weight {
|
||||
return Some(e.clone());
|
||||
}
|
||||
r -= e.weight;
|
||||
}
|
||||
None
|
||||
}
|
||||
/// 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) = self.weighted_entry(&entries) else {
|
||||
return;
|
||||
};
|
||||
let count = entry.min
|
||||
+ self
|
||||
.world
|
||||
.random
|
||||
.next_int_bound((entry.max - entry.min + 1) as i32)
|
||||
.unwrap_or(0) as u32;
|
||||
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 {
|
||||
@@ -516,171 +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<horizon_client::biome::SpawnEntry> = 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 = match self.structure_spawns(category, [x, y, z]) {
|
||||
Some(list) => list,
|
||||
None => match biome.spawns.get(category).cloned() {
|
||||
Some(list) => list,
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
let list: Vec<_> = list
|
||||
.into_iter()
|
||||
.filter(|e| self.res.mob_types.contains_key(&e.entity))
|
||||
.collect();
|
||||
let Some(e) = self.weighted_entry(&list) else {
|
||||
break;
|
||||
};
|
||||
group = e.min
|
||||
+ self
|
||||
.world
|
||||
.random
|
||||
.next_int_bound((e.max - e.min + 1) as i32)
|
||||
.unwrap_or(0) as u32;
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
//! 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>,
|
||||
/// Boxes of the mobs this pass created, not yet in the game's list.
|
||||
pending: std::cell::RefCell<Vec<Aabb>>,
|
||||
}
|
||||
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<String, Vec<SpawnEntry>>> {
|
||||
self.biome(x, y, z).map(|b| &b.spawns)
|
||||
}
|
||||
fn spawn_cost(&self, entity: &str, x: i32, y: i32, z: i32) -> Option<SpawnCost> {
|
||||
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<StructureAt> {
|
||||
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<f64> {
|
||||
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.pending.borrow().iter().any(|b| b.intersects(bounds))
|
||||
&& !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| spawn_selection::heightmap_blocks(self, kind, 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
|
||||
}
|
||||
}
|
||||
impl<'a> Game<'a> {
|
||||
fn natural_level(&self) -> GameLevel<'_, 'a> {
|
||||
GameLevel {
|
||||
game: self,
|
||||
w: self.mob_world_base(&[]),
|
||||
pending: Default::default(),
|
||||
}
|
||||
}
|
||||
/// 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<Mob>) -> Option<Spawned> {
|
||||
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<Mob>, 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<Counted> = 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| {
|
||||
let spawned = l.game.finalize_spawned(r, &mut pending);
|
||||
if let Some(s) = &spawned {
|
||||
l.pending.borrow_mut().push(s.bounds);
|
||||
}
|
||||
spawned
|
||||
};
|
||||
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| {
|
||||
let spawned = l.game.finalize_spawned(r, &mut pending);
|
||||
if let Some(s) = &spawned {
|
||||
l.pending.borrow_mut().push(s.bounds);
|
||||
}
|
||||
spawned
|
||||
};
|
||||
spawn_selection::spawn_mobs_for_chunk_generation(
|
||||
&level,
|
||||
source,
|
||||
(cx, cz),
|
||||
&mut random,
|
||||
&mut rules,
|
||||
&mut spawn,
|
||||
&mut |_| {},
|
||||
);
|
||||
}
|
||||
self.add_spawned(pending, true);
|
||||
}
|
||||
}
|
||||
@@ -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,83 +39,4 @@ impl Game<'_> {
|
||||
.map(|(n, _)| n)
|
||||
.collect()
|
||||
}
|
||||
/// `ChunkGenerator.getMobsAt` / `NaturalSpawner.mobsAt`: a structure's
|
||||
/// `spawn_overrides` for the category replace the biome's list where its
|
||||
/// box (or piece) holds `pos`; fortress spawns on nether bricks.
|
||||
pub(super) fn structure_spawns(
|
||||
&mut self,
|
||||
category: &str,
|
||||
pos: [i32; 3],
|
||||
) -> Option<Vec<horizon_client::biome::SpawnEntry>> {
|
||||
let reaching = self.structures_reaching(pos);
|
||||
if reaching.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let below = self.world.block(pos[0], pos[1] - 1, pos[2]);
|
||||
let bricks = &*self.res.facts.get(below).name == "minecraft:nether_bricks";
|
||||
for (id, piece) in &reaching {
|
||||
let Some(o) = self.spawn_override(id, category) else {
|
||||
continue;
|
||||
};
|
||||
if !o.0 || *piece {
|
||||
return Some(o.1);
|
||||
}
|
||||
}
|
||||
if category == "monster"
|
||||
&& bricks
|
||||
&& reaching.iter().any(|(n, _)| n == "minecraft:fortress")
|
||||
{
|
||||
return self
|
||||
.spawn_override("minecraft:fortress", "monster")
|
||||
.map(|o| o.1);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// A structure's override for a category: (piece-only, spawns).
|
||||
fn spawn_override(
|
||||
&mut self,
|
||||
structure: &str,
|
||||
category: &str,
|
||||
) -> Option<(bool, Vec<horizon_client::biome::SpawnEntry>)> {
|
||||
if !self.spawn_overrides.contains_key(structure) {
|
||||
let (ns, path) = structure
|
||||
.split_once(':')
|
||||
.unwrap_or(("minecraft", structure));
|
||||
let file = self
|
||||
.options
|
||||
.resources
|
||||
.join(format!("data/{ns}/worldgen/structure/{path}.json"));
|
||||
let v: serde_json::Value = std::fs::read(file)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
let mut map = std::collections::HashMap::new();
|
||||
for (cat, o) in v["spawn_overrides"].as_object().into_iter().flatten() {
|
||||
let piece = o["bounding_box"].as_str() == Some("piece");
|
||||
let spawns = o["spawns"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|e| {
|
||||
let count = &e["count"];
|
||||
horizon_client::biome::SpawnEntry {
|
||||
entity: e["type"].as_str().unwrap_or_default().to_owned(),
|
||||
weight: e["weight"].as_u64().unwrap_or(1) as u32,
|
||||
min: count["min_inclusive"]
|
||||
.as_u64()
|
||||
.or_else(|| e["minCount"].as_u64())
|
||||
.unwrap_or(1) as u32,
|
||||
max: count["max_inclusive"]
|
||||
.as_u64()
|
||||
.or_else(|| e["maxCount"].as_u64())
|
||||
.unwrap_or(1) as u32,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
map.insert(cat.clone(), (piece, spawns));
|
||||
}
|
||||
self.spawn_overrides.insert(structure.to_owned(), map);
|
||||
}
|
||||
self.spawn_overrides.get(structure)?.get(category).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ pub mod riders;
|
||||
pub mod shulker;
|
||||
pub mod sniffer;
|
||||
pub mod spawn_rules;
|
||||
pub mod spawn_selection;
|
||||
pub mod spawning;
|
||||
pub mod species;
|
||||
pub mod sulfur_cube;
|
||||
|
||||
@@ -43,6 +43,8 @@ pub enum Placement {
|
||||
pub struct MobData {
|
||||
pub states: Vec<StateData>,
|
||||
pub placements: HashMap<String, Placement>,
|
||||
/// Each entity type's `SpawnPlacements.getHeightmapType`.
|
||||
pub heightmaps: HashMap<String, String>,
|
||||
pub animations: HashMap<String, Animation>,
|
||||
/// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id.
|
||||
pub biome_tags: HashMap<String, std::collections::HashSet<String>>,
|
||||
@@ -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)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -82,7 +82,10 @@ impl Connection {
|
||||
}
|
||||
/// Connection.setEncryptionKey: both directions keyed with the shared secret.
|
||||
pub fn enable_encryption(&mut self, secret: &[u8; 16]) {
|
||||
self.reader.decrypt = Some(Cfb8::new(secret, secret));
|
||||
let mut decrypt = Cfb8::new(secret, secret);
|
||||
// Bytes already read past the last packet were sent encrypted.
|
||||
decrypt.decrypt(&mut self.reader.buffer);
|
||||
self.reader.decrypt = Some(decrypt);
|
||||
self.writer.encrypt = Some(Cfb8::new(secret, secret));
|
||||
}
|
||||
pub fn send(&mut self, body: &[u8]) -> Result<()> {
|
||||
@@ -180,4 +183,27 @@ mod tests {
|
||||
assert_eq!((id, payload.as_slice()), (9, &b"reply"[..]));
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
/// Encrypted bytes that arrive in the same read as the last plain packet
|
||||
/// are decrypted once encryption is enabled.
|
||||
#[test]
|
||||
fn encrypted_bytes_read_before_enabling_encryption() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let (sent, both_sent) = std::sync::mpsc::channel();
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).unwrap();
|
||||
c.send(&[0, 1, 2]).unwrap();
|
||||
c.enable_encryption(&[7; 16]);
|
||||
c.send(&[5, 4, 3]).unwrap();
|
||||
sent.send(c).unwrap();
|
||||
});
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut c = Connection::from_stream(stream).unwrap();
|
||||
let _keep_open = both_sent.recv().unwrap();
|
||||
assert_eq!(c.recv().unwrap(), (0, vec![1, 2]));
|
||||
c.enable_encryption(&[7; 16]);
|
||||
assert_eq!(c.recv().unwrap(), (5, vec![4, 3]));
|
||||
client.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user